kmtest icon indicating copy to clipboard operation
kmtest copied to clipboard

warning C4127: conditional expression is constant

Open wbuck opened this issue 3 years ago • 1 comments

So this particular warning can become an issue when compiling with /WX and /W4. The following can trigger this warning:

SCENARIO("Minimum operation")
{
    const int x{ 2 };
    const int y{ 3 };
    REQUIRE(x < y);
}

I believe re-writing the REQUIRE macro to the following would correct the issue:

#define REQUIRE(expression) \
do { \
    ++assertions; \
    const auto result__ = (expression); \
    if (!result__) { \
        KMTEST_ASSERT(const_cast<char*>(#expression), const_cast<char*>(__FILE__), __LINE__, nullptr); \
        ++failures; \
    } \
} while (0)

It looks like the C4127 was being generated when evaluating the constant expression in the if statement of the original REQUIRE macro.

Maybe some more testing is needed in order to fully confirm this is the case for different compiler versions. Currently I've only tested this with VS2019 version 16.11.13 and VS2022 version 17.1.4.

wbuck avatar May 27 '22 01:05 wbuck

I think the warning is good in such case. It means that the expression and the assert result is evaluated during compile time. So you can use static_assert and have error detection during compile time instead of run time.

SergiusTheBest avatar May 27 '22 07:05 SergiusTheBest

The issue is fixed!

SergiusTheBest avatar Aug 31 '23 15:08 SergiusTheBest

Thank you!

SergiusTheBest avatar Aug 31 '23 15:08 SergiusTheBest