C程序:output seems confusing

标签 c

#include<stdio.h>  
#include<conio.h>  
#define SQUARE(x) (x*x)  
void main()  
{  
    clrscr();  
    int i=3,j,k;  
    j=SQUARE(i++);  
    k=SQUARE(++i);  
    printf("\n%d\n%d\n%d",j,k,i);  
    getch();  
}  

答案令人困惑:9 49 7 我在想 j=3*4=12, k=6*7=42 , i=7 发生了什么事?我错过了什么吗? (x*x)=((x)*(x)) 同样在这里。没关系。

最佳答案

两行:

#define SQUARE(x) (x*x)  
j=SQUARE(i++); 

翻译成:

j = (i++ * i++);

这是未定义的行为。如果没有中间序列点(并且 * 不是序列点),您不得修改变量两次。

你最好使用类似的东西:

inline int SQUARE (int x) { return x * x; }

可能发生的情况是增量在乘法完成之前或之后一起发生,有效地给你:

i = 3;                  // i = 3
j = i * i; i++; i++;    // j = 9, i = 5
++i; ++i; k = i * i;    // i = 7, k = 49

但请记住,这就是这种情况下发生的情况。实现可以自由地以其他方式进行,因为您违反了规则。事实上,如果需要,它可以格式化您的硬盘。这就是未定义行为的本质,​​定义为(我的斜体):

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.

NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

关于C程序:output seems confusing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5181416/

相关文章:

c - 来自用户空间的内核驱动程序和 mmap

c - 产生段错误的节点

c - 使用损坏的 xml 中存在的 xml 的有效部分

c - 将一个表放入内存

c - gcc 在 amd64 上支持 128 位 int 吗?

c - 失去不稳定资格

c - 只打印数字,为什么输出这么奇怪?

c++ - libjpeg/libjpeg-turbo RGBA/32位int解压缩

c - 在c程序中使用宏

c - C 中的地址位置和地址位置的值