----- Original Message ----- From: "Pablo Manalastas" <[EMAIL PROTECTED]> To: "Abigail Manalastas" <[EMAIL PROTECTED]> Cc: <[EMAIL PROTECTED]>; <[EMAIL PROTECTED]> Sent: Tuesday, June 10, 2003 4:40 PM Subject: [plug] [OT] i++ and ++i
> 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. it is ok doc im not confuse :-> this is a well known *side effect* of *order of evaluation* :-> the order of evaluation like the above is NOT specified by any C specification anywhere... therefore you will see side effects or unwanted results from different compilers :-> here are some more side effects of order of evaluation: f() + g() a[i] = i++; f(x++, x++, x++) fooler. -- 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
