I see this statement: (20, 30, 50)
When I cout << (20, 30, 50);
it prints 50
.
When I rewrite it (a, b, c)
— a
, b
, c
can be char*
or int
— it always prints c
. Does anybody explain for me? Please.
I see this statement: (20, 30, 50)
When I cout << (20, 30, 50);
it prints 50
.
When I rewrite it (a, b, c)
— a
, b
, c
can be char*
or int
— it always prints c
. Does anybody explain for me? Please.
The infamous comma operator strikes again. The comma operator evaluates the arguments, and return the value after executing the last argument.
So in your case, (20, 30, 50) is interpreted by the program as a statement evaluating 20 being called, followed by one evaluating 30, followed by one evaluating 50. However, only the value of the last statement is seen, and hence the output is 50.
Here are some more questions on stack overflow related to the comma operator, which will help you better understand its effects:
What does the comma operator , do?
This is the comma operator. By default it evaluates the first argument and returns the second argument.
In your case, the expression (20, 30, 50)
will evaluate 20
and 30
, then return 50
.
Like most C++ operators, this can be overloaded, but you see it far less often than others.
In this statement
cout << (20, 30, 50);
expression (20, 30, 50)
is an expression with the comma operator. All operands except the last are discarded value expressions that is their results are not used and the value of the expression is the value of the last operand. For this expression it is 50.
Consider one more examples of using this operator that it would be more clear
int x = 10;
cout << ( ++x, ++x, ++x );
The output will be 13.
int x = 10;
cout << ( x++, x++, x++ );
The output will be 12.
If you want to output all values, 20, 30, 50, then you can use an initializer list. For example
for ( int x : { 20, 30, 50 } ) std::cout << x << std::endl;
The output will be
20
30
50