closed by
1,650 views
3 votes
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 ?
closed by

5 Answers

Best answer
1 votes
1 votes

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

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

Related questions

0 votes
0 votes
1 answer
2
2 votes
2 votes
2 answers
3
atulcse asked Jan 15, 2022
662 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 votes
0 votes
3 answers
4
ramakrushna asked Dec 23, 2021
689 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 sho...