Why is this code a non-constant condition?
static_assert(4294965 * 1000 / 1000 == -2, "overflow occurs");
But this is not:
const int overflowed = 4294965 * 1000 / 1000;
static_assert(overflowed == -2, "overflow occurs");
See code on godbolt. Note: With gcc <9 second code also has the error.
https://en.cppreference.com/w/cpp/language/constant_expression
Since it's unspecified if
gcc
will detect the undefined behavior, it may cause some strange case, like yours, when it detect only sometimeIf you change your
const
toconstexpr
you get the same errorclang seem fail both of your solution: https://godbolt.org/z/qocG8xfzb
Note:
Even if you find a way to
static_assert
an undefined behavior and you get the result you hoping for it does not mean that you can expect the same result later in the program.See : https://en.cppreference.com/w/cpp/language/ub
IMHO, most of the trick that try to "out-smart" the compiler with UB backfire sooner or later and should be avoided