你能解释一下下面的输出吗?

标签 c preprocessor-directive

请解释以下代码的输出:

#include<stdio.h>
#include<stdlib.h>

#define SQUARE(x) (x*x*x)

int main() {
  int x = 3;
  int y = SQUARE(++x)/x++; // Undefined behavior even though it doesn't look 
                       // like it here
  printf("%d %d",x,y);
  return 0;
}

输出:7 25

Please explain how the value of y comes to be 25?

最佳答案

该宏命名错误,但这只是转移注意力。这两个语句扩展为:

int x = 3;
int y = (++x * ++x * ++x) / x++;

这是未定义的行为,因为 x 在序列点之间被修改多次。编译器几乎可以做任何事情;它几乎可以以任何它想要的方式交错使用 x 以及 x 的前后增量。它可以从左到右执行操作,在这种情况下,您会得到:

int y = (4 * 5 * 6) / 6;

在此方案下,x 现在为 7,y 现在为 20。

它可以从右到左完成操作:

int y = (7 * 6 * 5) / 3;

现在,y 是 70。

它几乎可以在任何时候缓存 x 的值并使用它。尝试在各种编译器和各种优化级别下运行您的程序。 gcc -O4cc 有何不同?事实上,引用互联网术语文件:

nasal demons: n.

Recognized shorthand on the Usenet group comp.std.c for any unexpected behavior of a C compiler on encountering an undefined construct. During a discussion on that group in early 1992, a regular remarked “When the compiler encounters [a given undefined construct] it is legal for it to make demons fly out of your nose” (the implication is that the compiler may choose any arbitrarily bizarre way to interpret the code without violating the ANSI C standard). Someone else followed up with a reference to “nasal demons”, which quickly became established. The original post is web-accessible at http://groups.google.com/groups?hl=en&selm=10195%40ksr.com.

所以,我在这里会更加小心。你想让恶魔从你的 Nose 里飞出来吗?

关于你能解释一下下面的输出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18044138/

相关文章:

C程序来反转文件的内容并将其写入另一个文件

构建以冒号分隔的数据?

c - 选择上的 sqlite3_bind_text,准备好的 vs 字符串 SQL 语句的结果不同

MPI_Group 中排名的自定义排序

c - 使用预处理器指令在 C 中定义泛型函数

ios - 使用编译器条件来控制委托(delegate)实现?

c - MPI C 中的一般运行时间测量

c - 使 vim 缩进 C 预处理器指令与其他语句相同

objective-c - Xcode 中 #elseifdef 的预处理指令无效

C++ 停止预处理器宏扩展