Search code examples
c++cgcccompiler-warningssequence-points

Why does gcc not give a warning at undefined behaviour in code inside?


I just read this SO C++ FAQ about undefined behavior and sequence points and experimented a bit. In the following code gcc-4.5.2 gives me a warning only in the line mentioned in the code comment, although the one line before shows undefined behaviour too, doesn't it? You can't say which operand of addition is executed first (as + is no sequence point). Why does gcc not give me a warning in this line too?

int i=0;
int j=0;

int foo(void) {
    i=1;
    return i;
}

int main(void) {
    i = i + foo(); 
    j = j + (j=1); //Here is a rightly warning
    return 0;
}

Thank you for helping.


Solution

  • The behaviour of i = i + foo(); is unspecified but not undefined. Undefined means any possible behaviour is permitted, even aborting the program. Unspecified means either i is evaluated first, or foo(). Yes, foo writes to that same i, but since it happens in a separate statement, there is a sequence point before and after that store.