Why doesn't gcc give a warning when undefined behavior is inside the code inside?

I just read this SO C ++ FAQ about undefined behavior and sequence points and experimented a bit. In the following gcc-4.5.2 code, a warning appears only on the line specified in the code comment, although undefined behavior is displayed on one line before this, isn’t it? You cannot tell which addition operand is executed first (since + not a sequence point). Why doesn't gcc give me a warning on this line?

 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; } 

Thanks for the help.

+7
source share
3 answers

Behavior i = i + foo (); not specified, but not undefined. Undefined means that any possible behavior is allowed, even interrupting the program. Unspecified means that either I am evaluated first, or foo (). Yes, foo writes the same i, but since this happens in a separate statement, there is a sequence point before and after this store.

+16
source

String i = i + foo(); not defined in your program, but not undefined.

Compilers try to issue warnings without false positives (every time the compiler warns there is a defect that the programmer should fix) or, at least, with very low false positives. This means that in return they have quite a few false negatives. Consistent with the same philosophy, compilers do not usually warn of unspecified behavior.

To get a warning about your program, you should study static analyzers that are more aggressive with respect to warnings, at the cost of slightly more false positives. Static analyzers can very well decide to warn about unspecified behavior. Some of them even warn of certain behaviors, which, although defined, indicate that the programmer was probably confused.

+1
source

People see that calling foo () will change i, but for a computer program this is hard to understand. It is simply not intended for this.

-6
source

All Articles