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?
>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();
}