| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Postfix and Prefix....
Hi,
Here's a piece of code (C). ---------------------------------------- int y = 0, a = 0; y = a++ + a++ + a++; (1st exp) printf("Y: %d, A: %d\n",y,a); y = 0, a = 0; y = ++a + ++a + ++a; (2nd exp) printf("Y: %d, A: %d\n",y,a); ---------------------------------------- Could some please explain me the 1st expression and 2nd expression. ------------ Output: Y: 0, A: 3 Y: 7, A: 3 ------------ PS: I'm most confused on how Y is 7 is the 2nd expression. Thanks, Neville |
|
#2
|
|||
|
|||
|
Haha, that is a puzzler. I stared at that for quite a while and couldn't figure it but a friend of mine shed some light on it.
It has to evaluate one part of the addition to start with (denoted by brackets below) so lets say it evaluates it as - y = (++a + ++a) + ++a; To do this it must first increment a twice (since ++variable increments the variable before any other evaluation happens so at this point a = 2. Reducing it to - y = (2 + 2) + ++a; So it increment a again so now a = 3 giving us - y = (2 + 2) + 3; y = 4 + 3; y = 7; Hope this helps, -KM- |
|
#3
|
|||
|
|||
|
Results differ on different compiler
I did it on the latest MS VC++: Y=0, a=3 Y=9, a=3 On Linux using gc++ compiler: Y=0, a=3 Y=7, a=3 I think logically, the 2nd Y should be 6. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Postfix and Prefix.... |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|