Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma operator in c [duplicate]

#include<stdio.h>  int main(void) {    int a;    a = (1, 2), 3;     printf("%d", a);    return 0; } 

output: 2
Can any one explain how output is 2?

like image 849
Kr Arjun Avatar asked Sep 12 '17 13:09

Kr Arjun


People also ask

What is the comma operator in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.

Can we use comma in for loop in C?

The comma operator will always yield the last value in the comma separated list. Basically it's a binary operator that evaluates the left hand value but discards it, then evaluates the right hand value and returns it. If you chain multiple of these they will eventually yield the last value in the chain.

Can we use comma in for loop?

You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.

What is comma and sizeof operator in C?

The comma operator has no special meaning to sizeof . sizeof(b, a) examines the complete expression (b, a) , works out the resultant type, and computes the size of that type without actually evaluating (b , a) .


1 Answers

Can any one explain how output is 2?

Because the precedence of the assignment operator (=) is higher than the comma operator (,).

Therefore, the statement:

a = (1, 2), 3;

is equivalent to:

(a = (1, 2)), 3;

and the expression (1, 2) evaluates to 2.

like image 94
ネロク・ゴ Avatar answered Sep 19 '22 17:09

ネロク・ゴ