0

Discovered this by accident today after not paying attention to my find & replace commands in vim...

#include "iostream"

int main()
{    
    int number{number}; // wtf ?
    std::cout << "number=" << number << std::endl;    
}

Compiling with g++ -Wall produces the warning

main.cpp: In function ‘int main()’:
main.cpp:5:22: warning: ‘number’ is used uninitialized in this function [-Wuninitialized]
     int number{number};

as hoped.

Running the program produces the output

number=0

What the heck is going on here?

  • How can I create the variable number and initialize it to "number" - a variable which does not exist yet?
  • Does this produce undefined behaviour?
  • Is this a bug in gcc?
  • Is it not a bug for some technical reason*, but perhaps should it be considered to be something that you shouldn't be allowed to do? (If the rules of the syntax allow for this line of code to be valid, then perhaps should this be considered an exception and thus be illegal code?)
  • * If technical reason: What is the technical reason? How does gcc interpret the line of code int number{number}?
FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225
  • In a variable definition, the introduced identifier can be found by unqualified lookup earlier than most think ^^. Not a bug of the compiler. This is UB when `number` is used (am I right?) but this is a "no diagnostic required" ill-formed program. – YSC Mar 27 '18 at 14:53
  • This is not a bug, but a feature: https://stackoverflow.com/questions/11186261/why-is-int-i-i-legal – NathanOliver Mar 27 '18 at 14:55

0 Answers0