+ 1
Error: Control Reaches end of the non void function
Help me fix this code... Max of numbers using functions https://code.sololearn.com/c8Eo1SkvUNCq/?ref=app
9 ответов
+ 3
This is not an error, but a warning that the compiler does not see the "return" statement at the end of the return function.
Just add at the end of the function:
return 0;
+ 2
Emerson Prado, In this code, the "else" operator belongs to the last condition, curly braces are simply not put because they are not needed in this case:
if(c>d){
if(c>a && c>b){
return c;
}
}else return d;
Or:
if(c>d){
if(c>a && c>b)return c;
}else return d;
Or:
if(c>d && c>a && c>b)return c;
else return d;
And the code is quite working.
+ 1
The nested "if" blocks don't cover all possible situations
So the function can reach the end without running a "return" statement - required by its "int" return type.
Also, the else statement is not inside any if block. So it doesn't ever run.
Hints:
1. Study "elif" statements
2. Pay strong attention in "if"/"elif"/"else" matching - watch curly braces
3. Double check if you do need nesting
+ 1
Side note to Emerson's reply: "elif" is a Python keyword, you'll need to actually write out "else if" in C, like Bob Li did.
Additionally, this is a fine solution for such a small set of numbers, but it's also educational to think about how you might handle a much larger list (hint: use loops)
+ 1
Ajay Kumar
or use this:
int max_of_four(int a, int b, int c, int d){
int max = a;
if(b > a) max = b;
if(c > b) max = c;
if(d > c) max = d;
return max;
}
+ 1
Solo I got carried away by the indentation mismatch. Thanks for the correction!
+ 1
or this:
int max_of_four(int a, int b, int c, int d){
return a>b && a>c && a>d ? a :
b>c && b>d ? b :
c>d ? c : d;
}
+ 1
Emerson Prado ...😎🖐️
0
Ajay Kumar instead of trying to debug confusing nested structures, perhaps make it simpler by removing the unneccesary nesting:
int max_of_four(int a, int b, int c, int d){
if(a>b && a>c && a>d)
return a;
else if(b>a && b>c && b>d)
return b;
else if(c>a && c>b && c>d)
return c;
else return d;
}