c++gccgcc-warning

Iteraion 3u invokes unidenified error


#include <iostream>    
int main()
{
    for (int i = 0; i < 4; ++i)
        std::cout << i*5000000000 << std::endl;
}

getting a warning from gcc whenever i try to run this.

:-

warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations]
   std::cout << i*5000000000 << std::endl;

Whats the cause of this error?


Solution

  • Signed integer overflow (as strictly speaking, there is no such thing as "unsigned integer overflow") means undefined behaviour. Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.I suspect that it's something like: (1) because every iteration with i of any value larger than 2 has undefined behavior -> (2) we can assume that i <= 2 for optimization purposes -> (3) the loop condition is always true -> (4) it's optimized away into an infinite loop.

    What is going on is a case of strength reduction, more specifically, induction variable elimination. The compiler eliminates the multiplication by emitting code that instead increments i by 1e9 each iteration (and changing the loop condition accordingly). This is a perfectly valid optimization under the "as if" rule as this program could not observe the difference were it well-behaving. Alas, it's not, and the optimization "leaks"