I keep getting the following error (warning: control may reach end of non void function [-Wreturn-type])
This is what I have right now.
int min(int a, int b) {
if (b > a) {
return a;
}
if (a > b) {
return b;
}
}
I keep getting the following error (warning: control may reach end of non void function [-Wreturn-type])
This is what I have right now.
int min(int a, int b) {
if (b > a) {
return a;
}
if (a > b) {
return b;
}
}
If b == a
then there is no explicit return value. Your compiler is warning you of that.
This is why you should always use a final } else {
block.
Although adding
if (a == b){
return a; // either would do
}
would be an immediate fix, such a change could cause you problems in the future, if you ever write a version of min
that takes double
types, and one of the inputs is NaN
. No compiler I know of currently warns you of that.
Really though, you should ditch this function entirely and use the one from a respected library. For a whole host of technical reasons, the canonical way of writing min
is to use
return (b < a) ? b : a;
in
int min(int a, int b) {
if (b > a){
return a;
}
if (a > b){
return b;
}
}
you missed the case where a==b
can be just
int min(int a, int b) {
return (a < b) ? a : b;
}