[英]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.