[英]Confusion in C program
给定的程序定义是否正确?
#include <stdio.h>
int main()
{
int a=2,*f1,*f2;
f1=f2=&a;
*f2+=*f2+=a+=2.5;
*f1+=*f1+=a+=2.5;
printf("\n%d %d %d\n",a,*f1,*f2);
return 0;
}
否。带有*f2 += *f2 += ...
的位已经是未定义的行为。 同一对象的多个修改,而无需插入顺序点。 无需进一步寻找。
编辑 -当我说括号控制操作顺序时,我完全错了。 安德烈·T纠正我是正确的。 我发布的原始代码也有未定义的行为。 这是我的第二次尝试。 我的原始帖子也低于此帖子,因此可以看到更正。
最好的编码方法是将变量声明分成多行,以便您查看发生了什么。
//此代码是带有指针的实验
#include<stdio.h>
int main()
{
int a=2; //initialize a to 2
int *f1;
int *f2;
f1 = &a; //f1 points to a
f2 = &a; //f2 points to a
a += 2.5;
*f1 += a;
*f1 += a;
*f2 += a;
*f2 += a;
printf("\n%d %d %d\n",a,*f1,*f2);
return 0;
}
结果打印64 64 64
//我之前的错误代码如下:
#包括
int main()
{
int a=2; //initialize a to 2
int *f1;
int *f2;
f1 = &a; //f1 points to a
f2 = &a; //f2 points to a
a += 2.5; //2.5 + 2 = 4.5, but 4.5 as an int is 4.
*f1 += (*f1 += a); //4 + 4 = 8. 8 + 8 = 16.
*f2 += (*f2 += a); //16 + 16 = 32. 32 + 32 = 64.
printf("\n%d %d %d\n",a,*f1,*f2);
return 0;
}
结果打印64 64 64
您应该使用括号来保证首先进行哪些操作。 希望这可以帮助。 第一。 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.