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?

11
  • 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). Commented Jan 8, 2021 at 7: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. Commented Jan 8, 2021 at 7: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. Commented Jan 8, 2021 at 7:44
  • 1
    See the SECOND most upvoted answer of the duplicate I proposed. Commented Jan 8, 2021 at 8:01
  • 1
    please also read the linked question for this one. Commented Jan 8, 2021 at 8:26

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.