September 19, 2007

Two postfix operations in a single statement in GCC

#include <stdio.h>

int z = 11;

int main()
{
    printf("%d\n", ((z++) * (z++)));
    printf("%d\n", z);
    return 0;
}
$ gcc -o postfix_test.o postfix_test.c; ./postfix_test.o
121
12

Surprised? I sure was. It looks like gcc interprets two postfix operations in a single statement as a single postfix increment request. I guess this makes sense if you consider the postfix operator to mean, "Wait for this statement to complete, then have the variable increment." Assuming this specification, the second time that you postfix-increment the compiler says, "Yeah, I’m already going to have the variable increment when the statement completes — no need to tell me again."

On the other hand, prefix increment does work twice in the same statement. Maybe this is a decision that’s left up to the compiler? It’s not specified in K&R as far as I can see, but I haven’t checked any of the ANSI specifications.

Updates

2007/09/26 Here’s what Java has to say!

class DoublePostfixTester
{
    public static void main(String[] args)
    {
        int z = 11;
        System.out.println(((z++) * (z++)));
        System.out.println(z);
    }
}
$ javac DoublePostfixTester.java
$ java DoublePostfixTester
132
13

Which is what I would have expected in the first place. Bravo, Java — we’re more alike than I thought.