...">

G ++ "warning: iteration ... causes undefined behavior" for an obscure 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 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 do not understand why the increment causes undefined behavior. In addition, there are two changes, each of which warns of disappearance:

  • change line (*)tofor(int j...
  • change line (**)toif(!*p)

What is the meaning of this warning and why do the changes relate to it?

Note

$ g++ --version
g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
+4
source share
1 answer

undefined, i std::numeric_limits<int>::max() (2 31 - 1 32- LP64 LLP64), , undefined .

gcc 4294967296ul (2 32), 2147483646u (2 31), , i; - main, i - , 0. main , , i, , 2 32 - 2 31 - 1 .

  • "" , ; , if , &i . , gcc , i .

  • "" , gcc undefined . - i , , i . (. ), undefined, . , i , if , main -1.

+3

Source: https://habr.com/ru/post/1628007/


All Articles