Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

vgoklani

macrumors regular
Original poster
Jul 2, 2004
186
0
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

macrumors G3
Aug 30, 2003
8,634
0
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
Code:
#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:
Code:
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

Suspended
Nov 25, 2005
17,980
5,566
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 http://www.ansi.org for $18.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.