c++ - 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;
}
解决方案
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.
推荐阅读
- flutter - Flutter RawKeyboardListener 不适用于条形码扫描仪设备
- java - 使 class.getResource("/some.properties") 工作
- java - 是否需要关闭 Java 打开的进程?
- go - 为什么 Go 中的 bool 类型是 16 字节长?
- c# - Setting target to x86 in Visual studio code for 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine error
- javascript - jspdf 强制 pdf 放在一个位置,但我的 pdf 有大量数据,因此在一页中几乎看不到
- python - 如果比较 numpy 数组的语句引发 ValueError
- javascript - 函数内的 axios.get()
- python - 根据另一列中的类 (1,2,3) 将 NaN 值替换为一列中的所需值
- node.js - Node 控制台上没有错误,但无法按 Id 获取数据 - MERN 堆栈