Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using return vs no return in recursion?

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading