warning: control end of non-void function - c ++

0

I'm doing a function to return the maximum and I'm having problems ...

#include <iostream>
#include <cstdio>
using namespace std;

int max_of_four(int a, int b, int c, int d){
    if(a > b){
        if (a > c){
            if(a > d){
                return a; //
            }

            else return d; //
        }
    }
    else if(b > c){
        if(b > d){
            return b; //
         }

         else return d; //
    }


    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;
}

Why am I having this warning?

control reaches end of non-void function
    
asked by anonymous 02.01.2018 / 02:46

3 answers

2

The other answer already talks about the error . Maniero gives a viable solution, but perhaps not the desired one. I'll untangle here where it's missing and what's covered. Under the conditions, I'll put sequential lyrics to make it easier to mention.

To mention that the condition in A actually results, the condition of B also but that of E results in false, I will use the notation A,B,~E , where tilde ~ indicates that the comparison gave false.

if (A) {
  if (D) {
    if (E) {
      return a
    } else {
      return d
    }
  }
} else if (B) {
  if (F) {
    return b
  } else {
    return d
  }
} else if (C) {
  return c
} else {
  return d
}

Note that if conditions are A,~D , it will not reach any return . This is why the compiler generates a warning , because it is parsing that form.

I think the solution would be for else for condition D and put another structure of if-else inside ~D

    
02.01.2018 / 17:26
2

There is a situation that has no return and this can not happen, the function has to return something in all situations, it is probably only to remove else at the end and it will resolve because if all conditions fail it will execute something. / p>

The code is very confusing and has other problems, so I have a better time.

    
02.01.2018 / 03:04
1

Why do not you use a for instead of the various ifs. It will be less confusing and minor.

int max_of_four(int a, int b, int c, int d){
    int numbers[4]={a,b,c,d};
    int biggest=a;
    for(int i=0;i<4;i++){
        if(numbers[i]>biggest){ biggest=numbers[i]; }
    }
    return biggest;
}
    
09.01.2018 / 23:52