简体   繁体   English

C程序混乱

[英]Confusion in C program

Is the given program well defined? 给定的程序定义是否正确?

#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;
}

No. The bit with *f2 += *f2 += ... is already undefined behavior. 否。带有*f2 += *f2 += ...的位已经是未定义的行为。 Multiple modifications of the same object without an intervening sequence point. 同一对象的多个修改,而无需插入顺序点。 No need to look further. 无需进一步寻找。

edit - I was totally wrong when I said that parenthesis control order of operations. 编辑 -当我说括号控制操作顺序时,我完全错了。 AndreyT was right to correct me. 安德烈·T纠正我是正确的。 The original code I posted also had undefined behavior. 我发布的原始代码也有未定义的行为。 This is my 2nd Try. 这是我的第二次尝试。 My original post is also below this one so that the corrections can be seen. 我的原始帖子也低于此帖子,因此可以看到更正。

It is good coding practice to break up your variable declarations onto multiple lines so that you can see what's going on. 最好的编码方法是将变量声明分成多行,以便您查看发生了什么。

//This code is an experiment with pointers //此代码是带有指针的实验

#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;
}

result prints 64 64 64 结果打印64 64 64

// My Previous Incorrect code is below: //我之前的错误代码如下:

#include #包括

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;
}

result prints 64 64 64 结果打印64 64 64

You should use the parentheses to guarantee which operations occur first. 您应该使用括号来保证首先进行哪些操作。 Hope this helps. 希望这可以帮助。 first. 第一。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM