1
int foo(int i)
{
    if(i != 0)
        foo(i - 1);
    else
        return i;
}

GCC warns control reaches end of non-void function [-Wreturn-type].

Since the last return statement that set eax to 0, upon return from any other path, it returns 0. Also, compiler explorer produces the exact same code whether I wrote return foo(i - 1). Could one treat this as guaranteed behavior?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user2338150
  • 479
  • 5
  • 14
  • Your recursion construct must have a `base case`! That will have the "fall back" return statement compiler is looking for (since lookahead is limited, compiler cannot ascertain, when control will reach the return statement of your code). – anurag Jan 08 '21 at 07:42
  • If there were multiple return paths and one of the returns modified eax, this might not hold, is what I'm thinking. In this case, yes you're correct. – user2338150 Jan 08 '21 at 07:43
  • 5
    No you cannot treat it as guaranteed behaviour for the simple reason that the C++ standard says it is undefined behaviour. You're looking at the behaviour of your compiler not at the C++ standard. – john Jan 08 '21 at 07:44
  • `foo(1)` invokes `foo(0)` which returns 0 to the call `foo(1)`. Now, the control reaches end of `foo(1)` and there is no return. Hence the warning, because the return type was `int`. So, it is upto a compiler to decide what to do when a non `void` function doesn't return. **C/C++** cannot guarantee anything! – anurag Jan 08 '21 at 07:52
  • 1
    See the SECOND most upvoted answer of the duplicate I proposed. – Yunnosch Jan 08 '21 at 08:01
  • In this case, just drop the `else`. – Lundin Jan 08 '21 at 08:01
  • Thanks for the link. It is a slightly more complex disassembly, but the same that I was expecting. And I got it, this is just the particular compiler on the particular architecture. I shouldn't expect this as guaranteed behavior. – user2338150 Jan 08 '21 at 08:16
  • @Lundin: but if i dropped the else, code would behave differently without the return statement. – user2338150 Jan 08 '21 at 08:18
  • @anurag: so, you see now why such behavior cannot be guaranteed. – user2338150 Jan 08 '21 at 08:20
  • Well my conclusion is based on the accepted and now deleted answer! – anurag Jan 08 '21 at 08:24
  • 1
    please also read the linked question for this one. – user2338150 Jan 08 '21 at 08:26

1 Answers1

4

Could one treat this as guaranteed behavior?

Simple answer: No. You must have the return.

Also, compiler explorer produces the exact same code...

In C and C++ you can't rely on compiler output to figure out whether you're doing something correctly. Any time you invoke undefined behavior it's possible for the compiler to do anything at all. It might even do the thing you "expect" it to. If you infer from that that your code is fine you'll be misled. Correct behavior doesn't necessarily mean correct code.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578