Quoting Abigail Manalastas <[EMAIL PROTECTED]>:

> Dear Daddy,  
> How come the value of i is 5 in the following statements? 
>    i = 0;
>    i = i++ + ++i + i++ + ++i;

I tried compiling with gcc and running under Linux and
I got 7, not 5.  I tried figuring out the meaning, and I get 8.
Here is my own understanding of the meaning of the above:
Line 3 is the value that is actually added in the computation of i.
Line 4 is the current value of i at that time, just after
the indicated pre-increment or post-increment.

1.  i = 0
2.  i = 1++ + ++i + i++ + ++i;
3.      0   +   2 + 2   +   4
4.      1       2   3       4

And so the value obtained after addition in line 3 is 8.

To verify, I rewrote the program a bit as follows:

i = 0;
a = i++;
b = ++i;
c = i++;
d = ++i;
i = a+b+c+d;

And I got 8 as the value of i.

I guess the reason why gcc gives 7 in the original problem is that
gcc does automatic optimizations.  How 7 was obtained is beyond me.

I'm sorry if I confused you more than enlightened.

P~Manalastas


--
Philippine Linux Users' Group (PLUG) Mailing List
[EMAIL PROTECTED] (#PLUG @ irc.free.net.ph)
Official Website: http://plug.linux.org.ph
Searchable Archives: http://marc.free.net.ph
.
To leave, go to http://lists.q-linux.com/mailman/listinfo/plug
.
Are you a Linux newbie? To join the newbie list, go to
http://lists.q-linux.com/mailman/listinfo/ph-linux-newbie

Reply via email to