Reputation: 539
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.
Upvotes: 9
Views: 207
Reputation: 171167
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))
.
Upvotes: 14