Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ assignment precedence

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;
like image 658
WriteBackCMO Avatar asked Feb 09 '21 06:02

WriteBackCMO


People also ask

What is the precedence of assignment operator?

Operators are listed in descending order of precedence. If several operators appear on the same line or in a group, they have equal precedence. All simple and compound-assignment operators have equal precedence.

Which has higher precedence in C * or and?

Order of Precedence in Arithmetic Operators ++ and -- (increment and decrement) operators hold the highest precedence. Then comes * , / and % holding equal precedence. And at last, we have the + and - operators used for addition and subtraction, with the lowest precedence.

Is there order of operations in C?

C operators are listed in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.


1 Answers

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.

like image 99
Code-Apprentice Avatar answered Sep 22 '22 07:09

Code-Apprentice