5

Here is code to reverse an array using recursion

Using return rev(arr,++start,--end);

#include <iostream>
using namespace std;

void rev(int arr[],int start,int end)
{
    if(start >= end)
    {
        return;
    }
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    return rev(arr,++start,--end);
}

void reverse(int arr[],int size)
{
    rev(arr,0,size-1);
}

Using rev(arr,++start,--end);

void rev(int arr[],int start,int end)
{
    if(start >= end)
    {
        return;
    }
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    rev(arr,++start,--end);
}

void reverse(int arr[],int size)
{
    rev(arr,0,size-1);
}

They both give same output 7 6 5 4 3 2 1

What is the difference between using return and not using return with rev here?

4
  • 5
    In this specific example there is no difference because the return is the last statement of the function, and the thing being "returned" is void. You can confirm this by comparing the compiler output. They are identical. Commented Jan 8, 2022 at 3:28
  • Thanks for replying. I am new to recursion will you please explain it through some other example. Commented Jan 8, 2022 at 3:32
  • In many cases you want to return a value from recursion but in this case the function is a void function Commented Jan 8, 2022 at 3:34
  • Since rev() returns void, return rev(arr,++start,--end); is equivalent in net effect to rev(arr,++start,--end); return; or (since it is the last statement in the function before the closing }) to rev(arr,++start,--end); Commented Jan 8, 2022 at 3:43

1 Answer 1

4

There is no difference.

From 9.6.3 [stmt.return]:

A return statement with no operand shall be used only in a function whose return type is cv void, a constructor (15.1), or a destructor (15.4). A return statement with an operand of type void shall be used only in a function whose return type is cv void.

[...]

Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand.

Because the type of the function call expression is the cv-qualified return type of the function as defined in its signature, and because your function is defined to return void, then the three that follow are equivalent:

void f() {
    //stuff
    f();
    return;
}

void g() {
    //same stuff
    return g();
}

void h() {
    //same stuff
    h();
}
Sign up to request clarification or add additional context in comments.

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.