VOOZH about

URL: https://www.geeksforgeeks.org/cpp/return-by-reference-in-c-with-examples/

⇱ Return by reference in C++ with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Return by reference in C++ with Examples

Last Updated : 15 Jul, 2025

Pointers and References in C++ held close relation with one another. The major difference is that the pointers can be operated on like adding values whereas references are just an alias for another variable.

  • Functions in C++ can return a reference as it's returns a pointer.
  • When function returns a reference it means it returns a implicit pointer.


Return by reference is very different from Call by reference. Functions behaves a very important role when variable or pointers are returned as reference.

See this function signature of Return by Reference Below:
dataType& functionName(parameters); where, dataType is the return type of the function, and parameters are the passed arguments to it.
Below is the code to illustrate the Return by reference:
Output:
x = 20 The address of x is 0x7fff3025711c
a = 20 The address of a is 0x7fff3025711c
b = 20 The address of b is 0x7fff3025711c
x = 20 The address of x is 0x7fff3025711c
a = 13 The address of a is 0x7fff3025711c
Explanation:

Since reference is nothing but an alias(synonym) of another variable, the address of a, b and x never changes.

Note: We should never return a local variable as a reference, reason being, as soon as the functions returns, local variable will be erased, however, we still will be left with a reference which might be a security bug in the code.

Below is the code to illustrate the Return by reference:
Output:
10
Explanation: Return type of the above function retByRef() is a reference of the variable x so value 10 will be assigned into the x.
Comment
Article Tags: