Warning: control Reaches end of non-void Function - c++

Asked

Viewed 4,086 times

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 getting this warning?

control reaches end of non-void function
  • 1

    If the first if (a > b) enter and the if (a > c) from within not pass, its function contains undefined behavior.

3 answers

2

There is a situation that has no return and this can not happen, the function has to return something in all situations, probably just remove the else in the end and will solve because if all conditions fail he will perform something.

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

  • But doesn’t Isis guarantee that he will perform something, when all others fail? In the case of the example, when it does not return any of the others, it must return d.

2


The other answer already talks about the mistake. Maniero gives a viable solution, but perhaps not the desired one. I will unlock here where it is missing and what is covered. Under the conditions, I’ll put sequential letters to make it easier to mention.

To mention that the condition in A results in truth, the condition of B also but that of E result false, I will use the notation A,B,~E, where the Tilde ~ indicates that the comparison was 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 the conditions are A,~D, he won’t reach any return. This is why the compiler generates a Warning, because he’s analyzing this way.

I believe the solution would be for a else for the condition D and put another structure of if-else within the ~D

1

Why don’t you use a for instead of several ifs. It will get less confusing and smaller.

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;
}
  • One explanation is memory usage. Not to mention that in your for only 3 elements are needed, since a is a priori

  • True, but I don’t think memory would be a problem, it depends on where it will run this code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.