Return by Reference in C++ Function
On this page (6sections)
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
How It Works
This C++ program demonstrates Return by Reference in Function. It first prepares the data it needs, then uses conditional logic to decide the result, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Use conditional statements to handle the different cases.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Related Pages
Continue learning with these related tutorials and programs:
- C++ Tutorials — Browse all C++ Tutorials.
- C++ Function Basics — Tutorial — function syntax and calling conventions.
- Function Prototyping In C++ — More in functions in c.
- Function Types in C++ — More in functions in c.
Frequently Asked Questions
What does this C++ program do?
It is a C++ example program that demonstrates Return by Reference in Function, including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses conditional logic, illustrating a common pattern in C++ programming.