[英]I am getting a warning saying I have reached end of non-void function
I have a function that determines if a year is a leap year and I get a warning but I'm not sure where the warning is.我有一个函数可以确定一年是否是闰年,并且我收到警告,但我不确定警告在哪里。 It returns 1 if it is a leap year and 0 if it isn't.如果是闰年则返回 1,否则返回 0。
int isLeapYear(int yyyy) {
if (yyyy % 4 == 0) {
if (yyyy % 100 = 0) {
if (yyyy % 400 == 0) {
return 1;
}
else {
return 0;
}
}
else {
return 1;
}
}
}
Others have pointed out your error and offered alternative ways to code this.其他人指出了您的错误并提供了其他编码方法。 Let me offer another.让我提供另一个。 It's an early-return method that keeps the code flatter, shorter, and easier to understand:这是一种早期返回方法,可以使代码更扁平、更短且更易于理解:
bool is_leap(int y) {
if (y % 400 == 0) return true;
if (y % 100 == 0) return false;
return y % 4 == 0;
}
If yyyy % 4 == 0
evaluates false, if (yyyy % 4 == 0) { ... }
body is skipped, you return nothing.如果yyyy % 4 == 0
计算结果为 false, if (yyyy % 4 == 0) { ... }
主体被跳过,则您什么都不返回。 Add a return 0;
添加一个return 0;
to the very end.到最后。
Here's a different implementation:这是一个不同的实现:
#include <stdbool.h>
bool isLeapYear(int const year) {
if (year % 4) return false;
if (year % 100) return true;
return !(year % 400);
}
The way you've written this function, it's possible to exit without return
ing anything.根据您编写此函数的方式,可以退出而不return
任何内容。
int isLeapYear(int yyyy) {
if (yyyy % 4 == 0) {
...
}
<--- Nothing Is Returned Here
}
You should doing something like:你应该做这样的事情:
bool isLeapYear(int yyyy)
{
bool leapYear = false;
if (yyyy % 4 == 0) {
// If Leap Year Set leapYear To true
}
return leapYear;
}
The benefit of this is, there's only one exit point which makes it possible to set a default return
value and it's easier to read.这样做的好处是,只有一个退出点可以设置默认return
值并且更易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.