precedence in C

Discussion in 'Mac Programming' started by vgoklani, Feb 27, 2007.

  1. macrumors regular


    Jul 2, 2004
    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 ?
  2. macrumors G3


    Aug 30, 2003
    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 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.)
  3. macrumors G5


    Nov 25, 2005
    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 for $18.

Share This Page