0

I'm cross-compiling using ARM/GNU C Compiler:6.3.1 with optimizations -O0. A simple function like this:

static uint8_t xyzzy(void) {
  if (<predicate one>) {
    return 1;
  } else if (<predicate two>) {
    return 2;
  } else {
    return 4;
  }
}

results in an error message:

Error       control reaches end of non-void function [-Werror=return-type]

Is it really the case that the compiler doesn't know that one of those return statements must always be executed? Or is it me that is confused? And what is a recommended fix?

(P.S.: No, this is not a duplicate of Control reach end of non-void function, since I do have an else as the last clause.)

fearless_fool
  • 33,645
  • 23
  • 135
  • 217
  • 1
    [Can't reproduce](https://godbolt.org/z/rdaMM1bdj). Can you post an actual complete function? Also, gcc 6.3.1 is quite old, does this still happen with a newer version? – Nate Eldredge Sep 06 '21 at 19:48
  • I tried Mr. Godbolt's magnificent compiler explorer and can't reproduce it either. As for why gcc 6.3.1, that's what Microchip Studio (offshoot of Microsoft Studio) gives me to work with. I'll just work around the spurious error message. – fearless_fool Sep 06 '21 at 20:53

1 Answers1

1

Simply add a return statement at the end of your function. GCC considers that your function doesn't have a return statement.

static uint8_t xyzzy(void)
{
    if (<predicate one>) {
        return 1;
    } else if (<predicate two>) {
        return 2;
    } else {
        return 4;
    }
    return 0; // This will never be reached
}

You can get rid of unnecessary {}s and the elses:

static uint8_t xyzzy(void)
{
    if (<predicate one>)
        return 1;

    if (<predicate two>)
        return 2;

    return 4; // Executed if none of the above conditions are met.
}
Zakk
  • 1,935
  • 1
  • 6
  • 17