开发者

Confusion in C program

Is the given program well defined?

#include <stdio.h>
int main()
{
    int a=2,*f1,*f2;
    f1=f2=&a开发者_Python百科;
    *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. 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. 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

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

You should use the parentheses to guarantee which operations occur first. Hope this helps. first. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜