g++ “warning: iteration … invokes undefined behavior” for Seemingly Unrelated Variable
问题 Consider the following code in strange.cpp : #include <vector> using namespace std; int i = 0; int *bar() { ++i; return &i; } int main() { for(size_t j = 0; j < 99999999999; ++j) // (*) { const auto p = bar(); if(!p) // (**) return -1; } } Compiling this with g++ gives a warning: $ g++ --std=c++11 -O3 strange.cpp strange.cpp: In function ‘int main()’: strange.cpp:12:12: warning: iteration 4294967296ul invokes undefined behavior [-Waggressive-loop-optimizations] ++i; ^ strange.cpp:19:9: note: