+ 11

What is the logic ?

Guess the output of the following c++ code. #include<iostream> using namespace std; int main(){ int x=2,y=4,z=6,q; q = (x,y,z); cout<<q; return 0; } The output comes as 6. Can anyone help to to find out how ?

6th Apr 2019, 7:01 AM
Amlan Saha Kundu
Amlan Saha Kundu - avatar
8 Answers
+ 11
comma operator evaluates left values and returns last value https://stackoverflow.com/q/52550/9132046
6th Apr 2019, 7:25 AM
Mert Yazıcı
Mert Yazıcı - avatar
+ 7
Alex Schmidt It's only useful when first operand has a side effect. It doesn't have many use cases but you can see them here https://en.m.wikipedia.org/wiki/Comma_operator#Examples https://en.m.wikipedia.org/wiki/Comma_operator#Uses
6th Apr 2019, 9:23 AM
Mert Yazıcı
Mert Yazıcı - avatar
+ 6
«The comma operator links two expressions into one and guarantees that the leftmost expression is evaluated first. It is typically used to include more information in a for loop control expression. The value of the whole expression is the value of the right-hand expression.» C Primer Plus, By Stephen Prata
6th Apr 2019, 5:21 PM
Caveman
Caveman - avatar
+ 5
In this case it effectively means q=z.
6th Apr 2019, 11:39 PM
Sonic
Sonic - avatar
+ 1
Mert, why is that usefull? I mean I could always type q = z easy and simple
6th Apr 2019, 9:02 AM
Alex Schmidt
Alex Schmidt - avatar
+ 1
Thank you
6th Apr 2019, 9:24 AM
Alex Schmidt
Alex Schmidt - avatar
0
Exactly Sonic
7th Apr 2019, 7:55 AM
Alex Schmidt
Alex Schmidt - avatar
0
Z is the last value initialized to q , thats why output is 6
7th Apr 2019, 7:26 PM
Gull Afshan
Gull Afshan - avatar