• edited by
704 views
1 1 vote
Find the output ofthe following c code .

int fun1(int x);
int fun2(int x);

int main()
{
static int x=4;
x = (5>8?10:1!=2<5?fun1(++x): fun2(++x));
printf("Value of x:%d\n", x);
return 0;
}

int fun1(int x)
{
printf("x=%d\n", x);
return x;
}

int fun2(int x)
{
printf("x=%d\n", x);
return ++x;
}

(a) x=5
Value of x:6

(b) x=6
Value of x:6

(c) x=5

(d) None of these.
Value of x:5

1 Answer

Best answer
5 5 votes

Line: x = (5>8?10:1!=2<5?fun1(++x): fun2(++x)); consist multiple operators =, >,< ?:, !=. Hence, precednce and associativity of the operators needs to be identified to evaluate the expression.

OperatorPriorityAssociativity
>, <1Left to Right
!=2Left to Right
?:3Right to Left
=4Right to Left

 

$x = \color{red}({\underbrace{\color{black}{\underbrace{5>8}}?10:\color{green}{\underbrace{\color{green}{\underbrace{1!= \color{green}{\underbrace{2<5}}}}?\color{blue}{fun1(++x)}\color{green}{:}\color{magenta}{ fun2(++x)}}_{\text{due to Right associativity of Ternary Operator}}}}});$

 

Order of evaluation of ternary operator 

Source :K&R pg no. 51

 

The following ternary operation can be viewed like this :

if(5>8){
    x=10;
}
else if(1!=2<5){
    fun1(++x);
}
else{
    fun2(++x);
}

Since (5<8) so the else if resolves , now the following condition is evaluated as (1!=(2<5)) because $<$  has higher precedence than $!=$ . (1!=(2<5)) will give result as 0 as 1==1 and now this condition becomes false and we will resolve the else statement which will call the fun2 with increment value of x i.e $5$ .

$ fun2 $ will print the output $x=5$ and will return the updated value 6 , now  $var x$ of main will get the values as 6 , and it will print the output as $value of x =6$.

Answer: A

• selected by
Position:
Show:

Related questions

9 9 votes
3 3 answers
423
423 views
GO Classes asked Jun 17
423 views
What is the output of the following code?#include <stdio.h void update(int n, int *p) { if (n <= 0) return; *p = *p + n; update(n - 2, p); *p = *p + n; } int main() { int...
6 6 votes
2 2 answers
360
360 views
GO Classes asked Jun 17
360 views
What is the output of the following code?#include <stdio.h int fun(int n) { int x = n; if (n <= 0) return 0; x = x + 2; return x + fun(n - 2); } int main() { printf("%d",...
6 6 votes
2 2 answers
397
397 views
GO Classes asked Jun 17
397 views
How many times is $\texttt{fun()}$ called when the following code is executed? (Count the first call also).#include <stdio.h int fun(int n) { if (n <= 1) return 1; return...
6 6 votes
3 3 answers
367
367 views
GO Classes asked Jun 17
367 views
What is the output of the following code?#include <stdio.h int fun(int n) { if (n <= 1) return n + 1; if (n % 2 == 0) return fun(n - 1) + fun(n - 2); return fun(n - 2) + ...