C let's you shoot yourself in the foot here. TOTAL is an enumeration constant so is not known at preprocessing time. The C preprocessor thinks TOTAL is a macro. When it has to substitute a macro that is undefined in a constant expression, rather than doing the sensible thing of producing an error and failing, it silently substitutes zero. From the C spec (C11 6.10.1p4):Either done temporarily, or better in a unit-test file that's conditional on the particular target.Code:
#if TOTAL != <expected value>#error TOTAL has unexpected value#endif
I think this will work. _Static_assert is part of the C standard since C11.After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0, and then each preprocessing token is converted into a token
Code:
enum { TOTAL = 1};// Does not assert_Static_assert (TOTAL == 1, "TOTAL does not have expected value");#if TOTAL != 1// Produces an error because preprocessor treats TOTAL as 0 rather than 1#error TOTAL has unexpected value#endif
Statistics: Posted by alastairpatrick — Sat Mar 16, 2024 8:10 pm