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

107 Views Asked by At

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.

2

There are 2 best solutions below

3
NathanOliver On BEST ANSWER

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.

1
nullforce On

You could temporarily disable the warning for that code block, with a #pragma directive, as Mark Ransom suggests too.

template <bool B>
void foo(int x) {
#pragma warning(disable:4127)
    if (B && x == 0) { do_stuff(); }
#pragma warning(default:4127)
    do_other_stuff();
}

See: https://learn.microsoft.com/en-us/cpp/preprocessor/warning?view=msvc-170