Search code examples
c++c++11visual-studio-2019compiler-warningsc4127

Can I get MSVC to be less strict about "C4127: conditional expression is constant"


I'm using MSVC 16 2019 with many warnings turned on, including C4127: conditional expression is constant. However, I have code which looks like:

template <bool B>
void foo(int x) {
    if (B && x == 0) { do_stuff(); }
    do_other_stuff();
}

... and the warning is triggered when B is false.

I want to keep this error in general, but I don't want it to warn gratuitously when the constness of the condition expression is only due to template instantiation.

Note: This question is related, but - the code is not going to (significantly) change, so that's not what I'm asking. Not in C++17 either.


Solution

  • You can reformat the function to

    template <bool B>
    void foo(int x) {
        // Doing this to remove B triggering a constant condition warning when B is false
        // future: replace with if constexpr in C++17+
        bool b = B;
        if (b && x == 0) { do_stuff(); }
        do_other_stuff();
    }
    

    and now b is not a constant expression so the warning should not apply anymore.