0% found this document useful (0 votes)
27 views1 page

14 C++ Return by Reference

Uploaded by

Muluken Dejen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views1 page

14 C++ Return by Reference

Uploaded by

Muluken Dejen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Search tutorials and examples

C++ Return by Reference


In this article, you'll learn how to return a value by reference in a function and
use it efficiently in your program.

A DV E RT I S E M E N T S

In C++ Programming, not only can you pass values by reference to a function but
you can also return a value by reference.

To understand this feature, you should have the knowledge of:

Global variables

Example: Return by Reference

#include <iostream>
using namespace std;

// Global variable
int num;

// Function declaration
int& test();

int main()
{
test() = 5;

cout << num;

return 0;
}

int& test()
{
return num;
}

Output

In program above, the return type of function test() is int& . Hence, this
function returns a reference of the variable num .

A DV E RT I S E M E N T S

The return statement is return num; . Unlike return by value, this statement
doesn't return value of num , instead it returns the variable itself (address).

So, when the variable is returned, it can be assigned a value as done in


test() = 5;

This stores 5 to the variable num , which is displayed onto the screen.

Important Things to Remember When Returning by Reference.

Ordinary function returns value but this function doesn't. Hence, you cannot
return a constant from the function.

int& test() {
return 2;
}

You cannot return a local variable from this function.

int& test()
{
int n = 2;
return n;
}

Previous Tutorial: Next Tutorial:


C++ Recursion C++ Arrays

Share on: Was this article helpful?

A DV E RT I S E M E N T S

Related Tutorials

C++ Tutorial C++ Tutorial

C++ Storage Class C++ Call by Reference: Using pointers


[With Examples]

C++ Tutorial C++ Tutorial

C++ Multidimensional Arrays C++ Structure and Function

Tutorials Examples
Join our newsle er for the latest Python 3 Tutorial Python Examples
updates.
JavaScript Tutorial JavaScript Examples

Enter Email Address* Join C Tutorial C Examples

Java Tutorial Java Examples

Kotlin Tutorial Kotlin Examples

C++ Tutorial C++ Examples

Swi Tutorial

C# Tutorial

DSA Tutorial

Company Apps

About Learn Python

Advertising Learn C Programming

Privacy Policy

Terms & Conditions

Contact

Blog

Youtube

© Parewa Labs Pvt. Ltd. All rights reserved.

You might also like