+ 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 ?
8 ответов
+ 11
comma operator evaluates left values and returns last value
https://stackoverflow.com/q/52550/9132046
+ 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
+ 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
+ 5
In this case it effectively means q=z.
+ 1
Mert, why is that usefull?
I mean I could always type q = z easy and simple
+ 1
Thank you
0
Exactly Sonic
0
Z is the last value initialized to q , thats why output is 6