tags:

views:

127

answers:

2

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;
}
+8  A: 

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.

AndreyT
...because it modifies an object twice without an intervening sequence point. `*f1 += *f2 += ...` would be similarly undefined.
caf
as well as `*f2 += a += ...`
AndreyT
A: 

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.

Locklier
Really? Why then does it print `72 72 72` when I run the original code? :) Answer: the program does not have any specific or predictable output. The behavior of this program is *undefined*. The program is broken (that applies to the original code as well as to your version).
AndreyT
On top of that, parentheses in C do not make any guarantees about which operation will occur first. Parentheses affect grouping of operands and operators, not the order of evaluation.
AndreyT
I realize my mistakes. You're absolutely correct - I should have read your original post more carefully.
Locklier