Teen Programmers Unite  
 

 

Return to forum top

C/C++ Operator Precedence Rule

Posted by rassul [send private reply] at February 12, 2003, 01:53:59 PM

Hello,
Please help me understand the order of evaluation in the following code. Although it may not look practical but for me is to understand the rules. I am using MS compiler. The result from Java is: x=41, i=7, while from C is: x=36, i=7
I appreciate your help. Thanks
#include <stdio.h>
main()
{
int x = 0, i = 5;
x = i - ++i + (i++) * i;
printf("x=%d, i=%d\n", x, i);
}

Posted by CViper [send private reply] at February 12, 2003, 02:20:59 PM

not exactly what I call clean code...

my guess would be x = 5 - 6 + 6 * 7, which results in 41.

although, (i - ++i) seems to evaluate to 0. and (i++) * i[assuming i = 6] results in 36. Guess someone was smoking something bad. (And the author of the above isn't much better IMHO)

Posted by taubz [send private reply] at February 12, 2003, 09:07:47 PM

I would guess that using a ++/-- operator in the same expression with a second use of the same variable is not well defined across compilers.

Posted by Psion [send private reply] at February 12, 2003, 09:40:40 PM

We had all sorts of fun with such ambiguities in compilers class last semester. I'd avoid multiple uses of those side-effecting operators if I were you. It's really not worth learning the details of your compiler.

Posted by buzgub [send private reply] at February 12, 2003, 11:12:20 PM

Undefined.

http://www.eskimo.com/~scs/C-faq/q3.2.html

You must be logged in to post messages and see which you have already read.

Log on
Username:
Password:
Save for later automatic logon

Register as a new user
 
Copyright TPU 2002. See the Credits and About TPU for more information.