2

Is the following program really valid C++?

#include <string>   
int main () {
    std::string x = x;
    return 0;
}

It compiles without errors or warnings with g++ and just seg faults when run.

If I change the type of x to int, it gives me a warning at least: warning: "x" is used uninitialized in this function [-Wuninitialized].

I would have expected the line to be invalid because x has not been declared before.

rerx
  • 1,133
  • 8
  • 19
  • 1
    Related to [Has C++ standard changed with respect to the use of indeterminate values and undefined behavior in C++1y?](http://stackoverflow.com/q/23415661/1708801) my analysis in this [answer](http://stackoverflow.com/a/26767656/1708801) is also relevant ... that question is possibly a duplicate. – Shafik Yaghmour Nov 24 '14 at 14:49
  • Thanks for sharing this. I had not realized that this is actually an infamous example. – rerx Nov 24 '14 at 14:57

2 Answers2

2

Yes, it is well-formed. The point of declaration of the variable's name comes after the declarator std::string x, and before the initialiser = x, so the variable's name can be used in its own initialiser.

This allows well-defined initialisations that don't use the value, like:

void * p = &p;

but unfortunately also allows the uninitialised value to be used in examples like yours, with undefined behaviour.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Thanks for sharing that reasonable example. I'd still consider it a language bug that the original example has not been forbidden by the standard. – rerx Nov 24 '14 at 15:02
1

This is undefined behavior. As you are initialising one object with uninitialized object.

ravi
  • 10,994
  • 1
  • 18
  • 36
  • I realize that. But I would have expected this to be a corner case that could easily have been defined as invalid C++, resulting in a compiler error. – rerx Nov 24 '14 at 14:54
  • Why compiler would complain... Its syntactically right but logically wrong. – ravi Nov 24 '14 at 14:57
  • In a better world the line would be syntactically wrong C++. – rerx Nov 24 '14 at 15:05
  • Compilers give fatal error for syntactically correct programs all the time. char * a; int b = a; – brian beuning Nov 24 '14 at 15:12