Okay, many answers are already provided, but I couldn't really seem to find the solution.
Our task is to find the greatest of four integers.
https://www.hackerrank.com/challenges/functions-in-c/problem
When I run the following code:
#include <stdio.h>
/*
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;
}
*/
int max_of_four(int a, int b, int c, int d)
{
if(a>b)
{
if(a>c)
{
if(a>d)
return a;
}
}
else if(b>c)
{
if(b>d)
return b;
}
else if(c>d)
return c;
else
return d;
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
I am returned with this error at HackerRank:
Solution.c: In function ‘max_of_four’:
Solution.c:45:1: error: control reaches end of non-void function [-Werror=return-type]
}
^
cc1: some warnings being treated as errors
But the above code does it's job when run on Dev-C++ 5.11.
If we use the function inside the comments max_of_four
, and comment out the latter one, the job gets done as well.
If somebody could get me to know, how max_of_four
can be tweaked to get the code to work aptly, I'd be grateful.
And what's causing the error?
Is it an error or a warning? If so, why is a warning being treated as error?
When a function is not void and you use a if
statement to return the value, you must check that every case is really handled. This is not ensured by the last else in this case because you use nested statements which don't have a else
.
Here is a fixed version :
int max_of_four(int a, int b, int c, int d)
{
if(a>b)
{
if(a>c)
{
if(a>d)
return a;
}
}
if(b>c) //<====== I removed the else here to fix the implicit
// else of the previous form that was not handled
{
if(b>d)
return b;
}
if(c>d) //<===== Idem
return c;
else
return d;
}
Note however that the nested if
in you function could be replaced by and
which would be more compact :
int max_of_four(int a, int b, int c, int d)
{
if (a>b && a>c && a>d) return a;
else if(b>c && b>d) return b; // Here the else keys are kept even
else if(c>d) return c; // if they are not strictly necessary
else return d; // because of the return
}
Finally it would also be more reusable to write :
int max_of_two(int a, int b) { return a > b ? a : b; }
Because then you can reuse it for any number of parameters :
int max_of_three(int a, int b, int c) {
return max_of_two(max_of_two(a, b), c);
}
int max_of_four(int a, int b, int c, int d) {
return max_of_two(max_of_two(a, b), max_of_two(c, d));
}
//And so on
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments