> 文章列表 > 编译预处理:#if

编译预处理:#if

编译预处理:#if

用法

#if <expression>

#elif

#end

<expression> 是整数常量比较的表达式,例如:

  • defined表达式,例如 defined AAA, 或者 defined(AAA), 如果AAA是一个宏定义,return true,否则,return false;
  • 单个整数,例如:1/10/100/0, 非零为true,零为false;
  • 整数比较,例如:1 == 1为true, 0 == 0为ture, 1 > 2为false;
  • 单个的字符,例如:‘A’ == ‘A’ 为true, ‘A’ == 'C’为false, 我推测最终还是转化为ASIC码,然后进行整数的比较;
  • 如果出现两个未定义的变量,例如 AAA == BBB, 永远为true,我推测测试AAA和BBB都会被认为是零,即 0 == 0,所以永远为true;关于这一点,可以参考CppReference

After all macro expansion and evaluation of defined, __has_include (since C++17), and __has_cpp_attribute (since C++20) expressions, any identifier which is not a boolean literal is replaced with the number ​0​ (this includes identifiers that are lexically keywords, but not alternative tokens like and).
Then the expression is evaluated as an integral constant expression.

切记,

  • 不允许字符串的比较,例如 “AAA” == “AAA”, “AAA” == “BBB”, 编译会报错;