Search code examples
c++visual-studio-2010c4127

C4127: Conditional Expression is Constant


The following code generates warning C4127 (conditional expression is constant) in Visual Studio 2010 (where alias_wchar_t is an alias for wchar_t):

if (sizeof(alias_wchar_t) == sizeof(wchar_t)) // warning occurs here
{
    // do stuff
}
else
{
    // do other stuff
}

What's the most elegant way to resolve this, short of suppressing the warning?

The best solution I've come up with is to stuff the conditional into a static bool, and use that as the condition. There's a goodly amount of code above and below the if-else, so I wrap the whole thing in braces to limit the scope of the variable as much as possible:

// <snip>

{
    static bool isSameSize = (sizeof(alias_wchar_t) == sizeof(wchar_t));
    if (isSameSize)
    {
        // do stuff
    }
    else
    {
        // do other stuff
    }
}

// <snip>

This feels pretty gross though. This seems like it should be resolvable at compile-time rather than runtime, but the preprocessor doesn't know about sizeof. Is there a cleaner, more elegant way to resolve this?


Solution

  • It looks like you know what is going on, and you are fine with this.

    Compiler pragmas are meant for cases like that:

    __pragma(warning(push))
    __pragma(warning(disable:4127))
    if (sizeof(alias_wchar_t) == sizeof(wchar_t)) {
    __pragma(warning(pop))
    }
    

    Essentially, you are telling the compiler (and even more importantly, to human readers of your code) that you have reviewed the warning, and that you know what you are doing.