#include<stdio.h>
int main()
{
int x=10,y=12;
printf("%d",(x,y));
return 0;
}
The output of the program is 12. How?
#include<stdio.h>
int main()
{
int x=10,y=12;
printf("%d",(x,y));
return 0;
}
The output of the program is 12. How?
You're by chance using the comma operator.
In the C and C++ programming languages, the comma operator (represented by the token ,
) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).
That said,
printf("%d",(x,y));
is functionally equivalent to
printf("%d", y);
The expression that you are evaluating is:
x,y
This expression uses the comma operator. The standard (6.5.17 Comma operator) says:
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.
So, in your code, x,y
evaluates to y
, which has a value of 12
.
For a more expansive discussion, I refer you to cppreference.com. Although that discusses C++, the discussion for this operator is valid in the context of C. Particularly relevant to your question is this section:
The comma in various comma-separated lists, such as function argument lists (
f(a, b, c)
), initializer listsint a[] = {1,2,3}
, or initialization statements (int i, j;
) is not the comma operator. If the comma operator needs to be used in that context, it has to be parenthesized:f(a, (n++, n+b), c)
.
And that's exactly the situation in your question. If you had written:
printf("%d", x, y);
then there would have been no use of the comma operator, and you would have supplied one more argument to printf
than format specifier.
it is because first (x,y) is evaluated.
inside () the expression is x,y they are evaluated from left to right since the Associativity of Comma
operator is left to right
, so the last value of evaluating (x,y) is y.
read operator precedence and associativity rule
and how expressions are evaluated under operator precedence to understand these type of expressions