cgcc

Function calls order, is it a GCC bug?


Possible Duplicates:
Undefined Behavior and Sequence Points
Order of function call

I have found a problem in the following code when I compile it with GCC 4.5.2 (x86 32 bits).

# include <stdio.h>

int function(int x){
    printf("%d\n", x);
    return 2*x + 1;
}

int main(){
    int x = 3*function(1) + 4*function(2) + 5*function(3) + 6*function(4) + 7*function(5) + 8*function(6);
    printf("%d\n", x);
    return 0;
}

Expected output:
1
2
3
4
5
6
299

Actual GCC output:
1
2
4
3
6
5
299

I compiled the same code with clang and the output is the expected one.


Solution

  • No. The order the calls take place is not specified. They could take place in any order, but for each pair of function calls made here, one will see either all of the side-effects of the other, or none (i.e. they cannot run in parallel unless they have no side effects, and in this example they have a big side effect, printf).