Search code examples
c++c++11visual-studio-2013static-assert

Why is one expression constant, but not the other?


Why does Visual Studio 2013 compiler reject the first static assert (Error C2057), but not the second?

#include <limits>

typedef int Frequency;

const Frequency minHz{ 0 };
const Frequency maxHz{ std::numeric_limits<Frequency>::max() };
const Frequency invalidHz{ -1 };
static_assert(minHz < maxHz, "minHz must be less than maxHz");                // C2057
static_assert(invalidHz < minHz || invalidHz > maxHz, "invalidHz is valid");  // OK

Solution

  • I'd guess that, in that implementation, max() isn't constexpr (as C++11 says it should be), so that maxHz isn't a constant expression, while minHz and invalidHz are.

    Thus the first assert fails because it can't be evaluated at compile time; the second succeeds, because the comparison before || is true, so the second comparison isn't evaluated.