I was refactoring a term which appeared a bazilion times when by accident I produced a situation like in the code below:
#include "stdafx.h"
#include <iostream>
int foo = foo;
//By replacing with the following instruction we causes a compile error
//int foo(foo);
int _tmain(int argc, _TCHAR* argv[])
{
int bar = bar;
std::cout << "Well this is awkward " << foo << std::endl;
return 0;
}
With different debug and release configurations the compiler is silent about int foo = foo;
.
I fail to see a situation where this statement is not a bug waiting to happen. Shouldn't the Visual Studio compiler fire a warning?
I am not pretending this is an undefined behavior. I am saying that by default making an assignment from a variable to itself is likely to be the programmer mistake. Unless someone has a weird scheme around the use of the assignment operator.
A similar issue (
i=i++
) is indeed undefined behavior, but it's mainly because the instruction contains two assignments to the same variable:The incrementing of
i
(i++
), which is done at some point after the instructioni++
returnsi
The assignment of
i
The problem is that we can't really know if the assignment of
i
happens before or after incrementing, thus undefined behavior.In your example,
foo=foo
, we have a read, followed by a write. Unambiguously, we will have to read the value before writing to it, so it's easy to define.A side note is that if
operator=
is redefined, thenfoo=foo
could do a lot of things that aren't simply a copy of foo into itself. C++ purposefully allows you to shoot yourself in the food in many different ways. But in any case C++ compilers are not the gold standard of pro-activeness in warnings/errors.