-1

When I type my code like given below :

int a=10,b,c,d,e;
c= a++;
d = ++a;
e = ++a;
printf("value of c=%d, d =%d, e=%d",c,d,e);

it gives me an output like c =10 , d= 12, e=13 and when we add these values,i.e 10+12+13 becomes 35, but when I code it like :

b = a++ + ++a + ++a;
printf("value of b=%d" ,b);

it gives me output 36.

Can somebody describe what's the process behind this code and why the output of codes are different? Thank you!

0decimal0
  • 3,884
  • 2
  • 24
  • 39
Android developer
  • 129
  • 1
  • 1
  • 7

3 Answers3

0
int a=10,b,c,d,e;
c= a++;
d = ++a;
e = ++a;
printf("value of c=%d, d =%d, e=%d",c,d,e);

In statement c = a++ , value of a is used first(which is 10) and then incremented to11.
Statement d = ++a first increment a (which is 12 now) and then use its value to print in printf() statement.
Same for e = ++a.

Your second snippet

b = a++ + ++a + ++a;
printf("value of b=%d" ,b);

results in Undefined Behavior(http://en.wikipedia.org/wiki/Undefined_behavior)

haccks
  • 104,019
  • 25
  • 176
  • 264
0

Delicious Undefined Behaviour, the order of evaluation of the operands of + (and many others) is left to the implementation. So it's not even always 36 for the second case.

Kninnug
  • 7,992
  • 1
  • 30
  • 42
-1

Difference between them is second expression has not ended with a++ and yet to add some other values thats why a++ is 11, not 10

Kwag.degi
  • 7
  • 1