static_assert throws error 'non-constant condition for static assertion'

2.2k Views Asked by At

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.

1

There are 1 best solutions below

0
On

https://en.cppreference.com/w/cpp/language/constant_expression

A core constant expression is any expression whose evaluation would not evaluate any one of the following :

  • [...]
  • an expression whose evaluation leads to any form of core language undefined behavior (including signed integer overflow, division by zero, pointer arithmetic outside array bounds, etc). Whether standard library undefined behavior is detected is unspecified.

Since it's unspecified if gcc will detect the undefined behavior, it may cause some strange case, like yours, when it detect only sometime

If you change your const to constexpr you get the same error

constexpr int overflowed = 4294965 * 1000 / 1000;

clang 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

UB and optimization

Because correct C++ programs are free of undefined behavior, compilers may produce unexpected results when a program that actually has UB is compiled with optimization enabled

IMHO, most of the trick that try to "out-smart" the compiler with UB backfire sooner or later and should be avoided