Assigning two values ​​in parentheses in C

What this piece of code does in C:

p = (1, 2.1); 

What do we know about p ?

+4
source share
3 answers

The C comma operator is a sequence point, which means that expressions separated by commas 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 is assigned to the variable p .

Since the expressions in your example have no side effects, using a comma separator here makes no sense.

The brackets, on the other hand, are important because the assignment operator ( = ) is linked more strongly than the comma operator (has a higher priority) and will be evaluated before the comma operator without parentheses. So the result will be p == 1 .

+18
source

This is mistake. The comma operator is similar to :. He does one and then another. therefore (1.2.1) is estimated to 2.1

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

+1
source

all expressions expressed by commas will be evaluated from left to right, and the value of the rightmost expression will be returned.

therefore p will be 2.1.

0
source

All Articles