常量宏参数 [英] Constant macro parameters
问题描述
我怎样才能强迫一个宏接受整数常量或表达式,其值在编译期间确定?例如,如果
我们有:
#define TEST(X)等等等等等等
我想要将宏用作
x + = TEST(5);
y + = TEST(3 * 7);
>
而不是
z + = TEST(i);
z + = TEST(i * 3);
当我更喜欢编译时错误。
这可能在C中吗?
Ricardo Gibert< no ********** @ cox.net>写道:我怎么能强迫一个宏接受整数常量或表达式,其值在编译期间确定?例如,如果我们有:
#define TEST(X)等等等等我想要将宏用作
x + = TEST(5);
y + = TEST(3 * 7);
而不是
z + = TEST(i );
z + = TEST(i * 3);
当我更喜欢编译时错误。
这可能在C?
是的,在C89中(这是目前由几乎所有编译器实现的C标准)。
#define TEST(X)((void)sizeof(int [X]),X)
如果X不是
编译时常量。例如:
gcc -Wall -ansi -pedantic foo.c -o foo
foo.c:在函数中` main'':
foo.c:14:警告:ANSI C禁止变量大小数组'类型名''
foo.c:15:警告:ANSI C禁止变量大小的数组'类型名''
不幸的是,大多数编译器默认是不符合要求的,并且许多
它们实现了可变大小的数组延期,所以除非特别要求以
符合模式运行,否则他们不会发出这个必需的诊断。
此外,可变大小的数组是较新的C99 C标准的一部分,
所以这种方法也不适用于少数支持它的编译器。
- 凯文。
您可以利用表达式为情况下"构造
必须是无符号整数表达式。我正在考虑这些
行:
#define TEST(X){switch(1){case X :; } $
这是生成非常量
积分大小写表达式的错误诊断所必需的。
-
Stephan
" Ricardo Gibert" <无********** @ cox.net>在消息新闻中写道:< UJS5b.113549
How can I "force" a macro to accept integer constants or expressions whose value is determined during compilation? For example, if
we have:
#define TEST(X) blah blah with X
I want the macro to be used as
x += TEST(5);
y += TEST(3*7);
and not as
z += TEST(i);
z += TEST(i*3);
when I would prefer a compile time error.
Is this possible in C?
Ricardo Gibert <no**********@cox.net> wrote:How can I "force" a macro to accept integer constants or expressions whose value is determined during compilation? For example, if
we have:
#define TEST(X) blah blah with X
I want the macro to be used as
x += TEST(5);
y += TEST(3*7);
and not as
z += TEST(i);
z += TEST(i*3);
when I would prefer a compile time error.
Is this possible in C?
Yes, in C89 (which is the standard of C currently implemented by
virtually all compilers).
#define TEST(X) ((void)sizeof(int [X]), X)
This requires a diagnostic from a conforming C89 compiler if X is not a
compile-time constant. For example:
gcc -Wall -ansi -pedantic foo.c -o foo
foo.c: In function `main'':
foo.c:14: warning: ANSI C forbids variable-size array `type name''
foo.c:15: warning: ANSI C forbids variable-size array `type name''
Unfortunately, most compilers are by default non-conforming, and many of
them implement variable sized arrays as an extension, so they don''t
issue this required diagnostic unless specifically asked to run in
conforming mode.
In addition, variable sized arrays are part of the newer C99 C Standard,
so this method also doesn''t work on the few compilers that support it.
- Kevin.
Hi,
You might exploit the rule that the expression for a "case" construct
must be an unsigned integer expression. I was thinking along these
lines:
#define TEST(X) {switch(1) { case X: ; }}
This is required to produce an error diagnostic for a non constant
integral case expression.
--
Stephan
"Ricardo Gibert" <no**********@cox.net> wrote in message news:<UJS5b.113549
这篇关于常量宏参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!