#if defined(x)|| (y); 这有效吗?

lxu*_*usr 21 c

在一次审查中,我遇到了一段代码,如下所示:

#if defined(x) || y
Run Code Online (Sandbox Code Playgroud)

上述陈述是什么意思?条件是否正确执行?

oua*_*uah 25

是的,它是有效的.

这是标准(C99)在6.10p1中所说的内容:

if-group:
# if constant-expression new-line groupopt
# ifdef identifier new-line groupopt
# ifndef identifier new-line groupopt
Run Code Online (Sandbox Code Playgroud)

defined操作者被看作是一个常量表达式(6.10.1p1)的一元运算符的部分.

在您的示例中,如果x定义了宏,则将条件评估为true;如果定义了宏,则将条件评估为y不同0


Ric*_*III 12

对此的推理是双重的.

如果不使用的#ifdef,您使用的defined运营商,这样你可以在上面(使用逻辑运算符&&,||等等),让你不必复制你的代码,以便它适当地包括如果有多个标准,你需要定义.

此外,在我看来,我觉得阅读起来要容易#if defined(x)得多#ifdef x,你可以做到以下几点#if defined(x) && defined(y),而这是不可能的#ifdef.


Man*_*lio 5

是的,sincedefined(x)是一个布尔值,返回 true 或 false。

上述语句的意思是“要么x被定义,要么y为真”。