C语言支持语言级别的整数常量表达式。必须有可能找到一种方法利用这一点,以便只有符合此规范的值可以用于表达式,对吧?例如:
for (int i = 0; i < assert_constant(10); ++i) {...
一些部分解决方案并不足够通用,无法在多种情况下使用:
Bitfields: a classic strategy for implementing
static_assert
in C prior to C11 was to use a bitfield whose value would be illegal when a condition failed:struct { int _:(expression); }
While this could be easily wrapped for use as part of an expression, it isn't general at all - the maximum value of
expression
"[may] not exceed the width of an object of the type that would be specified were the colon and expression omitted" (C11 6.7.2.1), which places a very low portable limit on the magnitude ofexpression
(generally likely to be 64). It also may not be negative.Enumerations: an
enum
demands that any initializing expressions be integer constant expressions. However, anenum
declaration cannot be embedded into an expression (unlike astruct
definition), requiring its own statement. Since the identifiers in the enumerator list are added to the surrounding scope, we also need a new name each time.__COUNTER__
isn't standardized, so there's no way to achieve this from within a macro.Case: again, the argument expression to a
case
line must be an integer constant. But this requires a surroundingswitch
statement. This isn't a whole lot better thanenum
, and it's the kind of thing you don't want to hide inside a macro (since it will generate real statements, even if they're easy for the optimizer to remove).Array declaration: since C99, the array size doesn't even have to be a constant, meaning it won't generate the desired error anyway. It also again is a statement that requires introducing a name into the surrounding scope, suffering from the same problems as
enum
.
肯定有一种方法可以隐藏宏中的常量检查,使其可重复,通过(因此可以用作表达式),而不需要语句行或引入额外的标识符?