Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is `X x = x = X();` legal C++?

I reduced this:

struct A
{
   int * x;
   A() : x( x = new int() )
   {
   }
};

to the following:

int m = m = 3;
//or
struct X;
//...
X x = x = X();

Seems legal to me. I don't see why you'd want to do it, but is it legal? Are there cases where you'd want to do this (not the int case, I realize that's completely useless)?

like image 859
Luchian Grigore Avatar asked Mar 26 '12 08:03

Luchian Grigore


People also ask

What is the difference between X++ and ++X?

The Original Value of x is returned first then, x is incremented by 1. In the following example, x is incremented before the value it holds is used. Hope this helps! Originally Answered: What is the difference between X++ and ++X? X++ and ++x are different types of increment operators. 1 . X++ or in post increment operator,

What is the difference between x=x+1 and X++ in C++?

Let’s make it pretty simple. Both x++; & ++x; are syntactic sugar for the expression, x=x+1; x++ is Post-Increment, which in simple terms means that “First Use/Execute Then Change (present value)”. ++x is Pre-Increment, which in simple terms means that “First Change (present value) Then Execute/Use”.

What is the difference between ++X and B in C++?

Obviously, b is first used then changed. This will produce an output 160. Here b is first changed then it is used to evaluate the expression. Hope it Helps. Cheers!! ++x changes the value of x before it is used (pre-increment). x++ changes the value of x after it is used (post-increment).

How to solve X Plus X in Algebra?

How to solve x plus x in algebra? To solve x plus x, imagine the variable x as a familiar object, for example an apple. So now instead of x plus x, you have one apple plus one apple which is obviously two apples. Therefore if we think of x instead of apples, it is clear that the answer x plus x is 2x.


2 Answers

It depends on how you define "legal". It will compile; that doesn't mean that it is guaranteed to work.

Until the full statement X x = ... executes, x is uninitialized. It is not an X yet. Therefore, performing x = X() means to create a temporary X and call X::operator=(const X&) on the uninitialized variable x.

Calling a function on a non-POD class instance that has not been initialized (who's constructor has not yet been called) yields undefined behavior. If X is a POD type (or trivial in C++11), then it will work. But otherwise no.

like image 77
Nicol Bolas Avatar answered Nov 13 '22 01:11

Nicol Bolas


It's syntactically legal, but will result in undefined behavior at runtime. In a statement like:

X x = x = X();

the second = is assignment, and it assigns to an uninitialized variable. (The first = is simply the syntax for saying that what follows should be used for copy initialization; it isn't assignment.)

like image 36
James Kanze Avatar answered Nov 13 '22 01:11

James Kanze