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: containing loop
for(size_t j = 0; j < 99999999999; ++j) // (*)
^
I don't understand why the increment invokes undefined behavior. Moreover, there are two changes, each of which makes the warning disappear:
- changing the line
(*)
tofor(int j...
- changing the line
(**)
toif(!*p)
What is the meaning of this warning, and why are the changes relevant to it?
Note
$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4