Asterisk
Asterisk

Reputation:

Assignment of two values in parentheses in C

What does this piece of code in C do:

p = (1, 2.1);

What do we know about p?

Upvotes: 8

Views: 4796

Answers (3)

GG.
GG.

Reputation: 2951

all comma seprated expressions will be evaluated from left to right and value of rightmost expression will be returned.

so p will 2.1.

Upvotes: 0

Brian Postow
Brian Postow

Reputation: 12187

It's a mistake. the comma operator is similar to ;. It does the one, then the other. so (1,2.1) evaluates to 2.1

p will be 2.1 (or 2, if p is an int and needs to be truncated...)

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545578

The comma operator in C is a sequence point which means that the expressions separated by the comma are executed from left to right. The value of the whole expression is the value of the rightmost expression, in your case 2.1, which gets assigned to the variable p.

Since the expressions in your example don’t have side effects, the use of the comma separator here makes no sense whatsoever.

The parentheses on the other hand are important since the assignment operator (=) binds stronger than the comma operator (it has higher precedence) and would get evaluated before the comma operator without the parentheses. The result would thus be p == 1.

Upvotes: 21

Related Questions