in Programming in C edited by
1,755 views
1 vote
1 vote

Please explain the solution.The output is 11 7 0

#define MAX(x,y) (x) > (y) ? (x) : (y)
main()
{
int i = 10, j = 5, k = 0;
k == MAX(i++, ++j);
printf("%d %d %d", i,j,k);
}

What will the values of i , j and k?
 

in Programming in C edited by
1.8k views

4 Comments

12, 6, 0 ??
0
0
@Shubhanshu

it will give 11,7,0

there are brackets '()'....which have highest precedence and evaluated first before evaluating ternary operator
0
0
thanks!!
0
0

2 Answers

6 votes
6 votes
Best answer

Given i = 10, j = 5, k = 0

Lets see how line (5) k == MAX(i++, ++j); works..

  • Macro will replace MAX(i++, ++j) with (i++)>(++j):(i++):(++j);
  • line (5) becomes k==(i++)>(++j):(i++):(++j);

The order of evaluation will be [[k==(i++)]>(++j)]:(i++):(++j);

  • Put the values, the condition becomes
  • ((0==10)>6)     ->    0>6   --> Condition returns false!
  • So false part of ternary operator works  (++j) = 7

printf("%d %d %d", i,j,k); prints 11, 7 ,0

selected by
by
2 votes
2 votes
#define MAX(x,y) (x)>(y) ? (x):(y)
#include<stdio.h>

int main() {
    int i = 10;
    int j = 5;
    int k = 0;
    k == MAX(i++,++j);
    //becomes
    //k == (i++)>(++j) ? (i++):(++j);
    //k == 10 > 6 ? (i++) : (++j);, i = 11, j = 6
    //Here, > has the highest precedence followed by == and then ?
    //(k == (10 > 6)) ? (i++) : (++j);
    //(k == 1) ? (i++) : (++j);//this won't update k 
    //++j; 
    //k = 0, i = 11, j = 7
    printf("%d,%d,%d",i,j,k);
}

http://en.cppreference.com/w/c/language/operator_precedence

by

4 Comments

@Sukanya yes, and due to that j and ++j are printed using same printf and their evaluation order is undefined.
0
0
Thank you, @Arjun Sir for the detailed explanation.
1
1
Please read the answer -- the precedence part.
0
0