0
#include<stdio.h>
int main()
{
  int x=10,y=12;
  printf("%d",(x,y));
  return 0;
}

The output of the program is 12. How?

Masud Shaik
  • 81
  • 1
  • 1
  • 6

3 Answers3

4

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);
fredrik
  • 6,483
  • 3
  • 35
  • 45
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
4

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 lists int 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.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
0

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

LearningC
  • 3,182
  • 1
  • 12
  • 19
  • Can you provide any link to read operator precedence and associativity rule ? – Masud Shaik Mar 13 '14 at 16:34
  • @user3416257 you just want table then check [this](http://n.ethz.ch/~werdemic/download/week3/C++%20Precedence.html) or [this](http://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx). go through some expression evaluation examples too. – LearningC Mar 13 '14 at 16:40