Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Type name = name; ever useful in C++?

The following code is allowed in C++:

int a = a;

or

Type name = name;

Both lead to an uninitialized object being initialized by itself, which often leads to undefined behavior.

Is such code ever needed or reasonable? Are there cases of such code being useful?

like image 757
sharptooth Avatar asked Aug 01 '11 12:08

sharptooth


2 Answers

This reminded me of an old thread of the GCC mailing list in which Gabriel Dos Reis gave the following example to construct a one-node circular list:

struct Node {
  Node* link;
  Node(Node& n) : link(&n) { }
};

int main()
{
  Node x = x;
}
like image 179
adl Avatar answered Oct 21 '22 23:10

adl


You are allowed to use the name of the variable in its initializer. The code

Type name = name;

is probably not useful, but the code

Type name = f(&name);

might be.

There are many places where the language syntax doesn't forbid useless constructs. :-)

like image 42
Bo Persson Avatar answered Oct 21 '22 21:10

Bo Persson