关于#if宏定义中包含sizeof的问题
先贴下代码
#include<stdio.h>
int main()
{
enum
{
enum_val = 1,
};
const int i = sizeof(int);
#if enum_val
printf("enum\n");
#endif
#if i
printf("const\n");
#endif
}
在vs2013上,没有任何输出,这是什么道理?
还有,类似#if sizeof(int)这样的语句无法通过编译,又是什么原因?
C++ sizeof #if
[解决办法]
是不是因为宏是在预编译阶段处理的,而sizeof是在编译阶段处理的呢~
[解决办法]
sizeof是编译阶段的处理
enum也是
预编译语句里出现的enum_val,因为找不到定义,会被替换成空,空在#if语句里是当成false处理的,非零值才是当成true处理
[解决办法]
#if 后必须是constant-expression
[copied from MSDN]
The constant-expression is an integer constant expression with these additional restrictions:
- Expressions must have integral type and can include only integer constants, character constants, and the defined operator.
- The expression cannot use sizeof or a type-cast operator.
- The target environment may not be able to represent all ranges of integers.
- The translation represents type int the same as type long, and unsigned int the same as unsigned long.
- The translator can translate character constants to a set of code values different from the set for the target environment. To determine the properties of the target environment, check values of macros from LIMITS.H in an application built for the target environment.
- The expression must not perform any environmental inquiries and must remain insulated from implementation details on the target computer.