Sometimes it is necessary to compare a string's length with a constant.
For example:

if ( line.length() > 2 )
{
    // Do something...
}

But I am trying to avoid using "magic" constants in code.
Usually I use such code:

if ( line.length() > strlen("[]") )
{
    // Do something...
}

It is more readable, but not efficient because of the function call.
I wrote template functions as follow:

template<size_t N>
size_t _lenof(const char (&)[N])
{
    return N - 1;
}

template<size_t N>
size_t _lenof(const wchar_t (&)[N])
{
    return N - 1;
}

// Using:
if ( line.length() > _lenof("[]") )
{
    // Do something...
}

In a release build (VisualStudio 2008) it produces pretty good code:

cmp    dword ptr [esp+27Ch],2 
jbe    011D7FA5 

And the good thing is that the compiler doesn't include the "[]" string in the binary output.

Is it a compiler specific optimisation or is it a common behavior?

Edit
Report