Ann*_*yan -3 c++ compiler-errors return
我有一个Largest接受三个参数a、b和 的函数c。该函数旨在返回三个输入的最大值。但是,我在编译代码时遇到错误,指出该函数可能不会返回值。我不确定为什么会发生这个错误,因为我确实在函数中返回了一个值。
下面是我的 C++ 代码:
#include <stdexcept>
int Largest(int a, int b, int c) {
if (a > b && a > c) {
return a;
}
else if (a < b && b > c) {
return b;
}
else if (a < c && c > b) {
return c;
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助理解和解决此错误的帮助将不胜感激。
考虑这样的情况:
int l = Largest(1, 2, 2);
Run Code Online (Sandbox Code Playgroud)
使用这些参数,函数中的任何条件都不会是true:
if (a > b && a > c) { // 1 > 2 is false
return a;
}
else if (a < b && b > c) { // 1 < 2 is true, but 2 > 2 is false
return b;
}
else if (a < c && c > b) { // 1 < 2 is true, but 2 > 2 is false
return c;
}
Run Code Online (Sandbox Code Playgroud)
...因此该函数将结束,而不会返回int具有未定义行为的结果。
一个简单的修复:
if (a > b && a > c) { // 1 > 2 is false
return a;
}
else if (a < b && b > c) { // 1 < 2 is true, but 2 > 2 is false
return b;
}
else if (a < c && c > b) { // 1 < 2 is true, but 2 > 2 is false
return c;
}
Run Code Online (Sandbox Code Playgroud)
或者
int Largest(int a, int b, int c) {
return std::max(std::max(a, b), c);
}
Run Code Online (Sandbox Code Playgroud)
或更通用:
int Largest(int a, int b, int c) {
return std::max({a,b,c});
}
Run Code Online (Sandbox Code Playgroud)