This has been asked in an interview. What is the output 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;
}
By the output I am guessing its (1-3) = -2. But how from (3,2,1)
value 1
is chosen, similarly from (1,2,3)
value 3
is chosen? Am I right in what I am guessing?
Here, the comma operator and it's property is being used.
To elaborate, from C11
, chapter §6.5.17, Comma operator
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value
and, from C++11
, chapter § 5.18,
A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression (Clause 5). Every value computation and side effect associated with the left expression is sequenced before every value computation and side effect associated with the right expression. The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand, and is a bit-field if its right operand is a glvalue and a bit-field.
So, in case of a statement like
(3,2,1)-(1,2,3)
for the evaluation,
(3,2,1)
, 3 and 2 are (evaluated as a void
expression and) discarded, 1 is the value.(1,2,3)
, 1 and 2 are (evaluated as a void
expression and) discarded, 3 is the value.so, the statement reduces to 1 - 3
which is equal to -2
.
Same way, you can use for more elements, also.