首页 > 解决方案 > How do I fix this warning - "control reaches end of non-void function [-Wreturn-type]"

问题描述

During compiling, it shows this warning - control reaches end of non-void function [-Wreturn-type]. I googled and found that this warning shows when you don't return anything in the function. But I couldn't figure out where's the error in my code.

Here's my code:

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

int findUnique(int *a, int n){
    sort(a, a+n);
    int i=0;
    while(i<n){
        if(a[i]==a[i+1]){
            i += 2;
        }
        else{
            return a[i];
        }
    }
}

int main(){

    int t;
    cin >> t;

    while (t--){

        int size;
        cin >> size;
        int *input = new int[size];

        for (int i = 0; i < size; ++i)
        {
            cin >> input[i];
        }

        cout << findUnique(input, size) << endl;
    }

    return 0;
}

标签: c++

解决方案


The function returns nothing in case when the array does not contain a unique number or when the parameter n is equal to 0.

So the compiler issues the warning message.

Moreover the while loop can invoke undefined behavior when i is equal to n-1 due to using a non-existent element with the index n in this if statement

    if(a[i]==a[i+1]){

Also there is a logical error. The if statement

    if(a[i]==a[i+1]){
        i += 2;
    }
    else{
        return a[i];
    }

does not guarantee that indeed a unique number will be returned.

Using your approach when it is allowed to change the original array by calling the algorithm std::sort the function can be defined for example the following way

size_t findUnique( int *a, size_t n )
{
    std::sort( a, a + n );

    size_t i = 0;

    bool unique = false;

    while ( !unique && i != n )
    {
        size_t j = i++;

        while ( i != n && a[i] == a[j] ) i++;

        unique = i - j == 1;
    }

    return unique ? i - 1 : i;
} 

And in main the function can be called like

size_t pos = findUnique(input, size);

if ( pos != size )
{ 
   cout << input[pos] << endl;
}
else
{
    // output a message that there is no unique number
}

Pay attention to that your program produces multiple memory leaks. You need to free the allocated memory in each iteration of the while loop.


推荐阅读