-3

Compiled using GCC on a Fedora 20 Desktop, the following code outputs 10.

int x=10;
int y=5;
printf("%d",(y,x));
Anudeep Samaiya
  • 1,910
  • 2
  • 28
  • 33
  • 3
    comma operator evaluates to last value – mangusta Mar 09 '14 at 08:38
  • 2
    Refer http://stackoverflow.com/questions/1613230/uses-of-c-comma-operator – Pranit Kothari Mar 09 '14 at 08:40
  • @KarolyHorvath Another _newbie_ question this. – devnull Mar 09 '14 at 08:44
  • Hi guys it is true I am new here. So if anyone of you can show me how things work, it will be great help. – Anudeep Samaiya Mar 09 '14 at 08:55
  • 1
    @AnudeepSamaiya Most of the rules for writing good bug reports apply here, even though you are not reporting a bug. For instance, you said that you found the behavior of printing `10` strange, but you do not say why or what you expected. Considering that printing `10` is the correct behavior, that makes your question difficult to answer. Then, you invite people to post a random list of “puzzlers”. This is not how this site works. A stackoverflow answer is a solution to a programming problem that you face. Questions are not polls. It is all explained in http://stackoverflow.com/tour – Pascal Cuoq Mar 09 '14 at 12:03

3 Answers3

4

In C, (y,x) means evaluating x and y and returning only x. EG. From wikipedia:

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).

hivert
  • 10,579
  • 3
  • 31
  • 56
2

That´s the "comma operator" (not to be confused
with the comma when separating function parameters.)

The "result" is only the last part, but if the other parts are functions etc.,
they will be executed too.

deviantfan
  • 11,268
  • 3
  • 32
  • 49
1

In C (exp1,exp2)

First exp1 is evaluated, then exp2 is evaluated, and the value of exp2 is returned for the whole expression.

  1. (exp1, exp2) is like (exp1 && exp2) but both exp1 and exp2 will always be evaluated, whatever exp1 returns.
  2. (exp1, exp2) is like { exp1; exp2; } but it can be used as an expression in a function call or assignment.
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55