Reputation: 619
To make things more meaningful, basically for the below two cases.
I somehow imagined them to be similar, right hand side first.
But "=" just passes value through
"==" returns the result of the comparison "true" and then converts to 1.
So they are actually NOT similar?
int hehe = haha = 3;
int hehe = haha == 3;
//-----------------------------------------------
For the following code, can you explain why both haha and hehe are both 3?
I know assignment is right associative. So haha is assigned with 3 first.
But why the result of (haha = 3) is not 1 indicating something like the operation is successful? Instead 3 is propagating all the way to haha? What is the terminology of these two types: 3 propagates all the way vs some operation is successful.
int haha;
int hehe = haha = 3;
cout << haha << hehe;
Upvotes: 6
Views: 256
Reputation: 178
At the first line: A variable named "haha" is created.
At the second line:
Advice: Always initialize your variable at creation.
Upvotes: 0
Reputation: 384
Because, when assignment happens, all expression in the right side of the operator needs to be evaluated, then result becomes assigned to variable in the left side of the operator. when evaluating expression hehe = haha = 3
, OS should evaluate haha = 3
first. That is why hehe
equals haha
, and haha
equals 3
.
Upvotes: 2
Reputation: 83527
But why the result of (haha = 3) is not 1 indicating something like the operation is successful?
Because that is not how the C++ language specification says things works. Instead, the result of an assignment is the value that was assigned. In this case haha = 3
evaluates to 3
.
In C++, we never have "this operation was successful" for the built-in operators. In some cases, the compiler will give an error when you use an operator incorrectly. However, the compiler will just assume you know what you are doing if there is no error that it can find.
Upvotes: 3