Assignment of two values in parentheses in C

2020-07-19 07:05发布

What does this piece of code in C do:

p = (1, 2.1);

What do we know about p?

标签: c syntax
3条回答
Lonely孤独者°
2楼-- · 2020-07-19 07:18

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...)

查看更多
不美不萌又怎样
3楼-- · 2020-07-19 07:20

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.

查看更多
趁早两清
4楼-- · 2020-07-19 07:23

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

so p will 2.1.

查看更多
登录 后发表回答