edited by
407 views
1 votes
1 votes
In the below code Why I am getting the output as 10 instead of 11? .if I replaces k== with k= then the output is correct which is 11. is there any property of ternary operator behind this?

  
#include<stdio.h>

int main()
{
int i=10;
int k=0;
k==1>0?i++:2;

printf("%d", i);
return 0;
}
edited by

1 Answer

Best answer
7 votes
7 votes

Prerequisite for this question is Precedence and Associativity Rules and working principle of Ternaray Operator

 

Output depends upon the line k==1>0?i++:2;

 

1) k==1>0?i++:2; ===> By precedence and associativity rules, == operator having high priority than ?: operator

therefore the statement converted as ( ( k==1 ) > 0 ? i++ : 2 ) but note that output of this line is not assigned by any variable.

k==1 leads false therefore return 0, now  ( ( 0 ) > 0 ? i++ : 2 ) the ternary operator checks 0>0, it leads false therefore returning 2 but not executes i++

therefore k=0 and i=10

 

2) k=1>0?i++:2; ===> By precedence and associativity rules, = operator having less priority than ?: operator

therefore the statement converted as (  k = ( 1 > 0 ? i++ : 2 ) ) but note that output of this line is assigned to variable k

the ternary operator checks 1>0, it leads true therefore executes ( i++ and return the value to k )  but not returning 2

therefore k=10,i=11

 

Precedence and Associativity https://www.geeksforgeeks.org/c-operator-precedence-associativity/

Ternary Operator https://www.geeksforgeeks.org/cc-ternary-operator-some-interesting-observations/

selected by

Related questions

4 votes
4 votes
3 answers
1
2 votes
2 votes
2 answers
3
srestha asked May 12, 2019
1,080 views
Consider the following function $foo()$void foo(int n){ if(n<=0) printf("Bye"); else{ printf("Hi"); foo(n-3); printf("Hi"); foo(n-1); } }Let $P(n)$ represent recurrence r...