为什么我不能在#if 中使用sizeof()?
我有这个:
#if sizeof(int)
#error Can't use sizeof in a #if
#endif
我收到这个编译器错误:
missing binary operator before token "("
为什么我不能在这里使用 sizeof 运算符?
I have this:
#if sizeof(int)
#error Can't use sizeof in a #if
#endif
I get this compiler error:
missing binary operator before token "("
Why can't I use the sizeof operator here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于 sizeof() 是在预处理器运行后计算的,因此该信息对于
#if
不可用。C 编译器在逻辑上分为两个阶段,即使大多数现代编译器没有将它们分开。首先,对源进行预处理。这涉及计算并替换所有预处理器条件(#if、#define、用其替换词替换定义的词)。然后源代码被传递、处理到编译器本身。预处理器仅最低限度地了解 C 的结构,它没有类型知识,因此它无法处理像 sizeof() 这样的编译器级构造。
Because sizeof() is calculated after the preprocessor is run, so the information is not available for
#if
.C compilers are logically split into two phases, even if most modern compilers don't separate them. First, the source is preprocessed. This involves working out and substituting all the preprocessor conditionals (#if, #define, replacing defined words with their replacements). The source is then passed, processed, to the compiler itself. The preprocessor is only minimally aware of the structure of C, it has no type knowledge, so it can't handle compiler-level constructs like sizeof().
因为您只能在预处理器指令中使用文字常量。此外,sizeof(int) 总是大于 0,所以我相信这个#if 无论如何都会一直为真。
Because you can only use literal constants in a preprocessor directive. Besides, sizeof(int) is always larger than 0, so I believe this #if would be true all the time anyway.
考虑一下:
现在,这可能不是用正确的语法编写的,因为自从我上次使用 C++ 以来已经有一段时间了,但这一点仍然成立:)
Consider:
Now, this is prolly not written in the correct syntax as it's been a while since the last time I did C++, but the point still stands :)
只需使用普通的 if-else
编译器就会在编译时对其进行优化...
just use ordinary if-else
and compiler will optimize it in compile time...