PDA

View Full Version : precedence in C




vgoklani
Feb 28, 2007, 12:37 AM
int foo(int a){ return (++a * a++); }


int main()
{
cout << foo(5);

}


how does "return(++a * a++)" differ from "return(a++ * ++a)"?

that is, I get the same output (36 for both), but doesn't the postfix operator have a higher precedence than the prefix operator...which is operated on first, the first term or the second?

Is the order of precedence as follows:
++a > a > a++ ?

incidentally, I got similar results using this:

return (a++ * a) = return (a * a++) = 25 ?



iMeowbot
Feb 28, 2007, 01:13 AM
The missing bit of information is that the preincrement has higher precedence than * when on the left. The postincrement will not have an effect on the return value.

If you were to capture the postincrement so that it could be seen after the return (say, in a static variable or something stored in an object), you would find that a does get bumped up by 1 after the function return.


So, the output of this toy C program

#include <stdio.h>

static int y;

int foo (int x) {
y = x;
return (++y * y++);
}

int
main()
{
int a = 3;

printf("foo(%d): %d\n", a, foo(a));
printf("y: %d\n", y);
return 0;
}

would be:

foo(3): 16
y: 5


(with the external variable, you'll notice an interesting difference from your first case if you swap the y++ and ++y, thanks to scope goofiness. You may even get different results with different -O settings! Moral of the story: don't mix preincrement and postincrement like that, you're asking for trouble.)

gnasher729
Feb 28, 2007, 04:18 AM
int foo(int a){ return (++a * a++); }


int main()
{
cout << foo(5);

}


how does "return(++a * a++)" differ from "return(a++ * ++a)"?

that is, I get the same output (36 for both), but doesn't the postfix operator have a higher precedence than the prefix operator...which is operated on first, the first term or the second?

Is the order of precedence as follows:
++a > a > a++ ?

incidentally, I got similar results using this:

return (a++ * a) = return (a * a++) = 25 ?

What you are doing is defined by the C Standard as "undefined behavior". The same object (a) is modified twice without an intervening sequence point, which means _anything_ can happen. Serious bug in your program. It has nothing to do with precedence whatsoever.

Google for "C Standard Draft" and download the latest free draft of the C Standard, or buy a copy of the C Standard from www.ansi.org for $18.