简体   繁体   中英

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.

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. Add a 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM