brianSan
brianSan

Reputation: 535

Valid to use assignment operator in C expression?

Instead of

cardNumber = j+1;
deck[i][j] = cardNumber;
theDeck[k] = cardNumber;

is it valid to just say

deck[i][j] = theDeck[k] = cardNumber;

to assign cardNumber to both deck and theDeck at the same time??

Upvotes: 1

Views: 326

Answers (3)

Iceman
Iceman

Reputation: 4362

Yes it is; it is like this:

deck[i][j] = (theDeck[k] = cardNumber);

Upvotes: 0

sidyll
sidyll

Reputation: 59287

Yes, it's an expression and its value is the right side of the assignment. Note that this comes also from the associativity of = (right-to-left), which makes this:

x = y = z

Equivalent to:

x = (y = z)

But not:

(x = y) = z /* wouldn't work */

So you can go even further and write:

theDeck[k] = deck[i][j] = cardNumber = j+1;

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284796

Yes, it is. The assignment operator returns a value.

Upvotes: 5

Related Questions