Why does integer overflow on x86 with GCC cause an infinite loop? Why does integer overflow on x86 with GCC cause an infinite loop? c c

Why does integer overflow on x86 with GCC cause an infinite loop?


When the standard says it's undefined behavior, it means it. Anything can happen. "Anything" includes "usually integers wrap around, but on occasion weird stuff happens".

Yes, on x86 CPUs, integers usually wrap the way you expect. This is one of those exceptions. The compiler assumes you won't cause undefined behavior, and optimizes away the loop test. If you really want wraparound, pass -fwrapv to g++ or gcc when compiling; this gives you well-defined (twos-complement) overflow semantics, but can hurt performance.


It's simple: Undefined behaviour - especially with optimization (-O2) turned on - means anything can happen.

Your code behaves as (you) expected without the -O2 switch.

It's works quite fine with icl and tcc by the way, but you can't rely on stuff like that...

According to this, gcc optimization actually exploits signed integer overflow. This would mean that the "bug" is by design.


The important thing to note here is that C++ programs are written for the C++ abstract machine (which is usually emulated through hardware instructions). The fact that you are compiling for x86 is totally irrelevant to the fact that this has undefined behaviour.

The compiler is free to use the existence of undefined behaviour to improve its optimisations, (by removing a conditional from a loop, as in this example). There is no guaranteed, or even useful, mapping between C++ level constructs and x86 level machine code constructs apart from the requirement that the machine code will, when executed, produce the result demanded by the C++ abstract machine.