ANSI C 表达式的条件编译和编译时求值
我想做以下事情,但编译器不喜欢它:
unsigned short foo = 1;
// do something with foo
#if sizeof(short) * CHAR_BIT > 16
foo &= 0xffff;
#endif
我知道这个表达式总是可以在编译时完全求值,但也许它只在预处理器之后才求值?这在 ANSI C 中可能吗?还是我只需在运行时进行检查?
I would like to do the following, but the compiler doesn't like it:
unsigned short foo = 1;
// do something with foo
#if sizeof(short) * CHAR_BIT > 16
foo &= 0xffff;
#endif
I know this expression can always be fully evaluated at compile time, but maybe it's only evaluated after the preprocessor does it's thing? Is this possible in ANSI C or do I just have to do the check at run time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在预处理器表达式中使用
sizeof
。您可能想做这样的事情:You can't use
sizeof
in a preprocessor expression. You might want to do something like this instead:如果您的目标是在数据类型大小错误时停止编译,则以下技术很有用:
(sizeof() 函数在此由编译器而不是预处理器解释。)
此方法的主要缺点是编译器错误不是很明显。确保您写下非常清晰的评论。
If your aim is to stop compilation when a data type is the wrong size, the following technique is useful:
(The sizeof() function is interpreted here by the compiler, not the preprocessor.)
The main disadvantage of this method is that the compiler error isn't very obvious. Make sure you write a very clear comment.