Two destinations on the same line

I understand that such code is used in Objective C.

_conversation.lastMessageSentDate = message.sentDate = [NSDate date]; 

Do I believe that this code sets both conversation.lastMessageSentDate and message.sentDate to NSDate date ?

Or do I not understand this line of code?

Do other languages ​​have this formatting? I programmed in Python and Java and have never seen such code.

Thanks.

+4
source share
2 answers

These are not two declarations, these are two assignment operators. You are absolutely right in how this works.

The reason it works is because the assignment expression is a valid expression that produces a value. Rightmost assignment first evaluated

 message.sentDate = [NSDate date] 

and then the second assignment:

 _conversation.lastMessageSentDate = /*the result of the first assignment*/ 

Please note that this is an evaluation order, not an actual assignment order: they can occur in any order, because the order of side effects is not indicated in the absence of sequence points.

+5
source

Several assignments are common in many languages, people just use them less often than individual appointments.

Ruby does some interesting things with several assignments, such as:

 name, address1, address2, city, step = record.split(',') # split a CSV record into multiple fields 
0
source

All Articles