0

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;
    }
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
David Diaz
  • 19
  • 1
  • 3
    What do you think will happen when `a == b` ? Incidentally, you return the **min** value not the **max** in the question title. – Weather Vane Apr 06 '19 at 16:22
  • Possible duplicate of [Error: control may reach end of non-void function in C](https://stackoverflow.com/questions/22410538/error-control-may-reach-end-of-non-void-function-in-c) – Denis Zavedeev Apr 06 '19 at 16:34

2 Answers2

2

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;
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    *use the one from the C standard library.* I'm afraid there is no `min` function in the Standard C library. – chqrlie Apr 06 '19 at 16:48
  • @chqrlie Ha. That will teach me. I’ve edited. Could have sworn I had min, minf and so on at university. Posix perhaps? – Bathsheba Apr 06 '19 at 16:57
  • I had the same feeling and it took me a while to check in the Standard... There is `int abs(int)` and floating point versions `double fmin(double x, double y);`, `float fminf(float x, float y);` and `long double fminl(long double x, long double y);`, but no integer `min` nor a generic version. – chqrlie Apr 06 '19 at 19:28
1

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;
}
bruno
  • 32,421
  • 7
  • 25
  • 37