gpt4 book ai didi

C程序:output seems confusing

转载 作者:太空宇宙 更新时间:2023-11-04 05:21:29 26 4
gpt4 key购买 nike

#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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com