Redirected
edited by
1,819 views
1 votes
1 votes

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?
 

edited by

2 Answers

Best answer
6 votes
6 votes

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

Related questions

0 votes
0 votes
0 answers
2
2 votes
2 votes
2 answers
3
Parshu gate asked Nov 12, 2017
517 views
int i = 0 ;main( ){printf ( "\nmain's i = %d", i ) ;i++ ;val( ) ;printf ( "\nmain's i = %d", i ) ;val( ) ;}val( ){i = 100 ;printf ( "\nval's i = %d", i ) ;i++ ;}
0 votes
0 votes
0 answers
4
Na462 asked Aug 22, 2018
481 views
What will be output ?A. Abnormal Termination.B. Infinite loopC. Output wil be 65536D. NoneAns. D