• edited by
806 views
1 1 vote
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;
}

1 Answer

Best answer
7 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
Position:
Show:

Related questions

4 4 votes
3 answers 3 answers
1.8k
1.8k views
srestha asked May 20, 2019
1,828 views
#include<stdio.h #include<iostream int bar(int m, int n){ if(m==0)return n; if(n==0)return m; return bar(n%m,m); } int foo(int m,int n){ return(m*n/bar(m,n)); } int main(...
2 2 votes
1 1 answer
1.8k
1.8k views
srestha asked May 19, 2019
1,797 views
Consider the following $C$ implementation which when given $3$ numbers a,b,c as input, find the maximum of $3$ numbers $a,b,c.$int kickstart(int a,int b,int c) { if(B1) r...
2 2 votes
2 answers 2 answers
1.9k
1.9k views
srestha asked May 12, 2019
1,921 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...
1 1 vote
0 0 answers
2.2k
2.2k views
srestha asked May 10, 2019
2,196 views
Consider the following C code:int getNextGap(int gap){ gap=(gap*10)/13; if(gap<1)return 1; return gap; } void mystery(int a[ ],int n){ int gap=n; bool red=true; while(gap...