Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing the same variable that you're declaring

I've seen the following type mistake a couple of times while working with C++ code:

QString str = str.toUpper();

This can be a fairly easy mistake to make and yet it compiles and executes (sometimes with crashes, sometimes without). I can't see any circumstances under which it would be something that you'd actually want to do.

Some testing has revealed that the copy constructor is invoked, not the default one, and that the object is being given itself from within the copy constructor.

Can anyone explain why this isn't a compiler error, or even a warning?

like image 275
Chris Avatar asked Oct 10 '11 20:10

Chris


People also ask

Can variables be assigned and declared in the same statement?

It is also possible to declare a variable and assign it a value in the same line, so instead of int i and then i = 9 you can write int i = 9 all in one go. If you have more than one variable of the same type you can also declare them together e.g.

How do you reference a variable?

When a variable is declared as a reference, it becomes an alternative name for an existing variable. A variable can be declared as a reference by putting '&' in the declaration.

What does it mean when you say you are declaring a variable?

To declare a variable is to create the variable. In Matlab, you declare a variable by simply writing its name and assigning it a value.

Can you declare a variable more than once?

Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, care must be taken that the type and initialized value of the variable are handled correctly.


1 Answers

Technically the object str is defined when you reach the equal sign, so it can be used at that point.

The error is in trying to initialize the object with itself, and the compiler is allowed to warn about that (if it is able to detect it). However, as the detection is not possible in every case, the compiler is not required.

For example int x = f(x); is entirely correct if int f(const int&) doesn't use the value of its parameter. How is the compiler to know that if it hasn't seen the function body yet?

like image 134
Bo Persson Avatar answered Oct 16 '22 18:10

Bo Persson