• closed by
2,654 views
3 3 votes
closed with the note: Enough answers
#include<stdio.h>
int f(int a){
 a > 20 ? return 10: return 20;
}
int main(){
int b=fun(20);
return 0;
}

what will be the output of this program ?

5 Answers

Best answer
1 1 vote

It is an erroneous program.

Operators take expressions not statements. Function f(int) makes use of TERNARY OPERATOR, and just like any other operator, its operands (arguments) must be expressions.


The correct way to achieving the intended behaviour is this

#include<stdio.h>

int f(int a){
    if(a>20)
        return 10;
    else
        return 20;
}

int main(){
    int b=f(20);
    return 0;
}
• edited by
1 1 vote

To make this program errorless and execute with conditional operator, following things should be remember:

  • operator are defined with expressions not with keywords
  • function f should return a value 



#include<stdio.h>
int f(int a){
    return a > 20 ? 10 : 20;
}
 
int main(){
    int b = f(20);
    printf("%d ", b);
    return 0;
}
0 0 votes
Let's assume your function defined and called are same, either fun(int) or f(int).  exp1 = expression 1 and so on

So z= exp1 ? exp2 : exp3 is calculated as: evaluate exp1 and if it's non-zero then evaluate exp2 and assign z to exp2 value otherwise  evaluate exp3 and assign z to exp3 value. here return are statements; not expressions.

There won't be any output.
• edited by
0 0 votes

Please do not confuse in ternary operators 

you can consider the code like this

int f(int a){
    if(a>20)
        return 10;
    else
        return 20;
}

int main(){
    int b=f(20);
    return 0;
}

this code will execute properly and will return 0 because main function is returning 0; 

int b=f(20); this statement stores value returned by f()

20 will be returned if in main we write return b;

Position:
Show:

Related questions

1 1 vote
1 answers 1 answer
1.4k
1.4k views
abhinowKatore asked Jan 18, 2023
1,432 views
What will be the output of the following program ?answer is 8 but I am getting 5, please explain where I am wrong
2 2 votes
2 answers 2 answers
1.1k
1.1k views
atulcse asked Jan 15, 2022
1,121 views
Consider the following programint find (int n) { int a = 1; for (i = 1; i < = n; i ++) for (j = 1; j < = i; j++) for (k = 1; k <= j, k++) a = a + 1; ...
0 0 votes
3 3 answers
1.6k
1.6k views
ramakrushna asked Dec 23, 2021
1,561 views
What should be the ans. Isn’t the Function initialization should be outside main function? They are given inside main. If declaration would be outside main then ans shoul...