Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using return; in recursion functions

Tags:

c++

return

#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?

like image 244
user2546419 Avatar asked May 05 '26 06:05

user2546419


2 Answers

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.

like image 144
Mr. Llama Avatar answered May 06 '26 18:05

Mr. Llama


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.

like image 21
NathanOliver Avatar answered May 06 '26 20:05

NathanOliver