3
#include <stdio>
using std::cout;
void CountDown(int N) {
  if(N == 0) {
    return;
  }
  cout << N;
  CountDown(N-1);  
  //return;
}

In the code the output I get when return is commented is same as when not commented.

What I want to ask is whether it makes a difference if I use a return; statement at the end of the function (since it would implicitly return to the function, which called it, at the end of the braces)?

Another question: What if had a function with a return type instead of void here. I tried it with a function. The value was wrong.But there was no compiler error. So using simply a return; makes no difference right? Except when I want to prematurely end the function right?

8
  • 1
    It makes no difference whether you put return; at the end of a function returning void. This has nothing to do with recursion, it is always true. Commented Sep 2, 2015 at 14:17
  • Mmm. In that code, the last return; is never reached, isn't it? But in any case, that sentence is no necessary in void functions. Commented Sep 2, 2015 at 14:18
  • 1
    See what is the purpose of return in the void function Commented Sep 2, 2015 at 14:19
  • Re updated question, falling off the end of a value returning function is undefined behavior see this question ... because it is undefined behavior no diagnostic is required. Commented Sep 2, 2015 at 14:34
  • @ShafikYaghmour I didn't get it.What does undefined behaviour mean.And how does it affect the program? I mean its not a compiler error right? Commented Sep 2, 2015 at 14:41

2 Answers 2

4

For void return functions, no it doesn't make a difference. However, if the function is expected to return anything but void, then you'll need to include a valid return for all code paths.

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

4 Comments

There is no code path that would reach beyond the call to CountDown(N-1)
well, your answer is of course still correct, I just thought one might misunderstand it
@tobi303 why not? I mean when (n==0) case would be done and that function will return to the function CountDown(1) then the return; statement would be executed right?After the calling CountDown(0) part.
hm yes you are right. I faster in writing than thinking, my mistake
2

At the end of a void function control is automatically returned to the calling function so you do not need a return; at the end. return in a void function is used to exit the function before it normally would like in your if statement.

If you have a function that is supposed to return a value and does not then that is undefined behavior.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.