Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-assignment of variable in its definition

Tags:

c++

The following C++ program compiles just fine (g++ 5.4 at least gives a warning when invoked with -Wall):

int main(int argc, char *argv[])
{
  int i = i; // !
  return 0;
}

Even something like

int& p = p;

is swallowed by the compiler.

Now my question is: Why is such an initialization legal? Is there any actual use-case or is it just a consequence of the general design of the language?

like image 753
piripiri Avatar asked May 31 '17 20:05

piripiri


2 Answers

This is a side effect of the rule that a name is in scope immediately after it is declared. There's no need to complicate this simple rule just to prevent writing code that's obvious nonsense.

like image 97
Pete Becker Avatar answered Oct 03 '22 20:10

Pete Becker


Just because the compiler accepts it (syntactically valid code) does not mean that it has well defined behaviour.

The compiler is not required to diagnose all cases of Undefined Behaviour or other classes of problems. The standard gives it pretty free hands to accept and translate broken code, on the assumption that if the results were to be undefined or nonsensical the programmer would not have written that code.

So; the absense of warnings or errors from your compiler does not in any way prove that your program has well defined behaviour. It is your responsibility to follow the rules of the language. The compiler usually tries to help you by pointing out obvious flaws, but in the end it's on you to make sure your program makes sense.

And something like int i = i; does not make sense but is syntactically correct, so the compiler may or may not warn you, but in any case is within its rights to just generate garbage (and not tell you about it) because you broke the rules and invoked Undefined Behaviour.

like image 45
Jesper Juhl Avatar answered Oct 03 '22 20:10

Jesper Juhl