Can someone clean up this concept from the output I am getting?
This was asked in an interview. What is the result of the below snippet?
#include <iostream>
using namespace std;
int main() {
cout << (3,2,1)-(1,2,3) << endl; // in C++ too this prints -2
printf("%d\n",(3,2,1)-(1,2,3)); // prints -2
printf("%d\n",("%d",3,2,1)-(1,2,3)); // prints -2
return 0;
}
From the result, I guess it (1-3) = -2. But how is selected from (3,2,1)
value 1
, similarly from (1,2,3)
value 3
selected? Am I right in my guessing?
source to share
Here is the comma operator and its property is used.
To develop, from C11
, chapter ยง6.5.17, the Comma operator
The left operand of the comma operator evaluates to a void expression; there is a sequence point between its evaluation and the point of the correct operand. The right-hand operand is then evaluated; the result has its own type and value
and, from C++11
, chapter ยง 5.18,
A comma-separated pair of expressions are evaluated from left to right; the left expression is a discarded value expression (section 5). Each value calculation and side effect associated with the left expression is sequenced before each value calculation and side effect associated with the correct expression. The type and value of the result is the type and value of the correct operand; the result has the same value category as its right-hand operand, and is a bit-field if its right-hand operand is a glvalue and a bit-field.
So in case of type assertion
(3,2,1)-(1,2,3)
for rate,
-
(3,2,1)
, 3 and 2 (evaluated as expressionvoid
and) are discarded, 1 is the value. -
(1,2,3)
, 1 and 2 (evaluated as an expressionvoid
and) are discarded, 3 is the value.
so the operator boils down to 1 - 3
, which is -2
.
The same can be used for other elements as well.
source to share
You should consider the comma operator (,)
The comma operator (,) is used to separate two or more expressions that are included, where only one expression is expected. When a set of expressions needs to be evaluated by value, only the rightmost expression is considered.
In your case:
(3,2,1) //evaluates to 1
(1,2,3) //evaluates to 3
source to share
The Comma operator always returns the last value, i.e.
- in your first
cout
it is 1-3 = -2 - Further, in
printf
again this is 1-3 = -3 - finally in the last one
printf
, it is again 1-3 = -2
The Comma operator always solves all leftmost expressions (operands) and simply returns the rightmost operand as the result rvalue
.
source to share