Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize C++ const variable with itself

Just now I had a bug of the following sort:

#include <iostream>

const int i = i;

int main(void)
{
    /* not allowed by default, but with -fpermissive */
    //const int i;
    /* allowed by default, even without -fpermissive. Seems to initialize to 0 */
    for ( int j = 0; j < i; ++j )
        std::cout << "hi";
    /* i = 0 */
}

Compiled with:

g++ const-init.cpp -Wall -Wextra -pedantic -O2

Because the compiler silently initialized i to 0 some loops were optimized away. The error happened because of a copy-paste error.

Is this 'feature' valid and/or documented somewhere? What is it even good for? Does it have a name?

Edit: Without -O2 g++ behaves like I would want it to behave: it issues the following error

const-init.cpp:8:19: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
     const int i = i;
                   ^

So why does the compiler assume 0 for i when using the -O2 Flag and even deletes the whole loop because of this assumption?

like image 707
mxmlnkn Avatar asked Aug 18 '26 19:08

mxmlnkn


1 Answers

Its name is "undefined behaviour" and setting i to 0 is just one possible outcome.

like image 146
rici Avatar answered Aug 21 '26 10:08

rici