GangstaGraham
GangstaGraham

Reputation: 9355

Two Assignments On One Line

I understand that such code is used in Objective C.

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

Am I right in assuming that this code sets both conversation.lastMessageSentDate and message.sentDate to NSDate date?

Or am I misunderstanding this line of code?

Do other languages have such formatting? I have programmed in Python and Java and never saw any code like this.

Thanks.

Upvotes: 4

Views: 1017

Answers (2)

Richard Brown
Richard Brown

Reputation: 11436

Multiple assignments are common in many languages, people just use them less frequently than single assignments.

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

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

These are not two declarations, these are two assignment statements. You are absolutely correct about the way it works, too.

The reason that it works is that an assignment expression is a valid expression that produces a value. The rightmost assignment gets evaluated first

message.sentDate = [NSDate date]

and then the second assignment:

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

Note that it's the order of evaluation, not the order of actual assignments: these may happen in any order, because the order of side effects is not specified in the absence of sequence points.

Upvotes: 5

Related Questions