Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the comma operator being used here? [duplicate]

Possible Duplicate:
C++ Comma Operator
Uses of C comma operator

I am not new to C++, but this is the first time I see the following code:

int a=0;
int b=(a=2,a+1);

That is C++ code. Can you tell me what is going on here? And how variable b gets value 3?

like image 868
seeker Avatar asked Dec 05 '22 14:12

seeker


2 Answers

This code is equivalent to this:

int a = 2 ; 
int b = a + 1 ;

First expression to the left of comma gets evaluated, then the one to its right. The result of the right most expression is stored in the variable to the left of = sign.

Look up the comma operator for more details.

http://en.wikipedia.org/wiki/Comma_operator

like image 182
Coding Mash Avatar answered Dec 09 '22 15:12

Coding Mash


(a = 2, a + 1); return 3 because in general case operator (a, b) return b, and calculation in (a, b) started from right to left. So, in your case, (a = 2, a + 1) return a + 1, and after operator a = 2 was executed a + 1 return 3.

like image 37
Mikhail Viceman Avatar answered Dec 09 '22 14:12

Mikhail Viceman