LLVM and GCC, different output code

This is a sample code to show a different result from the LLVM compiler and GCC. I wonder why? The answer should be very simple, but I don't see it. (Xcode 4.6.1)

Code:

#include <stdio.h>

#define MAX(a,b) ( (a) > (b) ? (a) : (b) )

int increment() {
    static int i = 42;
    i += 5;
    printf("increment returns %d\n",i);
    return i;
}

int main( int argc, char ** argv ) {
    int x = 50;
    printf("max of %d and %d is %d\n", x,increment(),MAX(x, increment()));
    printf("max of %d and %d is %d\n", x,increment(),MAX(x, increment()));
    return 0;
}

      

LLVM output:

increment returns 47
increment returns 52
increment returns 57
max of 50 and 47 is 57
increment returns 62
increment returns 67
increment returns 72
max of 50 and 62 is 72

      

GCC output:

increment returns 47
increment returns 52
max of 50 and 52 is 50
increment returns 57
increment returns 62
increment returns 67
max of 50 and 67 is 62

      

+2


source to share


2 answers


Parameter estimation order is not specified ... So:

printf("max of %d and %d is %d\n", x,increment(),MAX(x, increment()));

      



cause unspecified behavior undefined The . This is why you have different results for both compilers.

Another (potential) problem: MAX

- This can cause two calls increment

. Avoid using such macros.

+13


source


The LLVM code gives the correct ANSI C results. If you don't want the increment to be called more than once in a print statement, store the return value in a variable and use that. Mentally stepping through the code, the display should be incrementing 47 incrementing back 52 incrementing back 57 Maximum 50 and 47 is 57 increment 62 increment returning 67 max. 50 and 62 equals 72 So my initial reaction and learning of the code was wrong and the LLVM output was right. The reason for the LLVM result is that the increment is called three times for each print statement in the main. The way to make this output print sensible output is to store the value returned by incrementing the variable and print the variable, not another call to increment. The difference in results is independent of undefined behavior,as far as I know, but from ANSI C correct or incorrect conformance.



-2


source







All Articles