给定的程序是否定义明确?
#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;
}
给定的程序是否定义明确?
#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 += ...
已经是未定义的行为。对同一对象进行多次修改,而没有中间的序列点。没必要再看下去了。
编辑-当我说括号控制操作顺序时,我完全错了。AndreyT 纠正了我是对的。我发布的原始代码也有未定义的行为。这是我的第二次尝试。我的原始帖子也在此帖子下方,以便可以看到更正。
将变量声明分解为多行是一种很好的编码习惯,这样您就可以看到发生了什么。
//这段代码是一个带指针的实验
#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
您应该使用括号来保证首先发生哪些操作。希望这可以帮助。第一的。希望这可以帮助。