-3

The following code:

void main
{
    int b=10;
    int a=5;
    printf("%d",(b,a));
}

This gives an output 5 on execution. Can anyone explain the reason for it?

I expected an output 10 since that is the first value that matches "%d".

Maroun
  • 94,125
  • 30
  • 188
  • 241
user11
  • 1

2 Answers2

3

Read about the comma operator. Your (b,a) expression is evaluated to 5 (the value of a).

Also, take the good habit of ending your printf format control strings with a newline \n or else call sometimes fflush (which gets automatically called after main, using atexit techniques). Remember that <stdio.h> streams are buffered!

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
1

In C, (b,a) means "calculate b, then calculate and return a". So, It's practically the same as just a in your case.

Gassa
  • 8,546
  • 3
  • 29
  • 49