Return By Reference in C++ Function


Syntax

function_name(arguments..) = assignment_reference_value;

max(a,b) = 1000;

Return By Reference in C++ Function Example Program

//Simple Return By Reference Function Example Program in C++
//Function Example

#include<iostream>
#include<conio.h>

using namespace std;
int c;
int & max(int &x, int &y);

int main() {
   int a = 200, b = 100;
   cout << "Simple Return By Reference Function Example Program\n";
   
   //Works a as Normal Function
   c = max(a,b);
   cout << "\nValues a :"<<a<<" b:"<<b;
   cout << "\nMax Is:"<<c;

   //Works a as Return By Reference Function
   max(a,b) = 1000;
   cout << "\nValues a :"<<a<<" b:"<<b;
   
   a = 50;
   b = 100;
   max(a,b) = 1000;
   cout << "\nValues a :"<<a<<" b:"<<b;
   getch();
}

// Return By Reference Function
int & max(int &x, int &y) {
  if(x > y)
  	return x;
  return y;
}

Sample Output

Simple Return By Reference Function Example Program

Values a :200 b:100
Max Is:200
Values a :1000 b:100
Values a :50 b:1000