Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluation order of double assignment

Tags:

c++

I've found something in our codebase that, even if it has never failed, doesn't look "right" to me.

I've trimmed the code down to something akin to a linked list (the data structures are much more complex than that).

Node * node = firstNode();

while( moreNodesAwaiting() )
{
    Node * newnode = giveMeAnotherNode();

    node = node->next = newnode ; // <-- This is what I don't like.
}

I'm not sure if undefined behaviour applies here. We're modifying both the data structure and the pointer to it between sequence points, but that's not the same as modifying the value twice.

Also, if the compiler can evaluate elements of an expression in whatever order, does it mean that it can evaluate node->next BEFORE the assignment takes place?

Just in case, I've changed it to something like:

    node->next = newnode ;
    node = node->next    ;

which also emphasizes the fact that we traverse the list.

like image 604
Diego Sánchez Avatar asked Jun 24 '13 13:06

Diego Sánchez


People also ask

What is the typical evaluation order for an assignment operator?

5.17 Assignment and compound assignment operators In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

What is a double assignment?

In highly-object-oriented languages, double assignment results in the same object being assigned to multiple variables, so changes in one variable are reflected in the other.

What are multiple assignments in Python?

Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.

What is chained assignment in Python?

In Python, assignment statements are not expressions and thus do not have a value. Instead, chained assignments are a series of statements with multiple targets for a single expression.


1 Answers

Assignments associate right-to-left. In other words:

a = b = c;

is parsed as

a = (b = c);

and this order is guaranteed by the standard.

That is, for primitive types, it will assign c into both b and a. For non-primitive types, it will call a.operator= (b.operator= (c)).

like image 140
Angew is no longer proud of SO Avatar answered Oct 14 '22 19:10

Angew is no longer proud of SO