Function returning by reference – CSKC
Sign In

Search

Code Learning #CPP#2749    siteicon   siteicon  

Function returning by reference

A program to demonstrate returning of a reference data type from the function.

Learning Objectives

  • Use of function which can return location of returned variable rather than the value of it.

Source Code

TC++ #2749

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

int& setg();
This function prototype with & marked immediately after the return data type. This means that functions instead of returning a value is actually returning a reference to a location where the value is stored.

int g=10; //This global declaration of variable g with initial value set as 10.

cout<<“Global var g before change = “<<g<<endl; //The initial value is printed here

setg()=20;
This would look different to you as the function call is on the left hand side of assignment. This perfectly okay as left side is supposed to be an address to an location. This function is actually a reference returning function so it is actually a place where something is stored. So whatever place it is pointing to it will store 20 after this assignment is made.

cout<<“Global var g after function call = “<<g<<endl;
The newly changed value will be printed here.

int& setg() { return g; }
This function simply returns the location pointing to g. This location must be a global or static location so that it can become available to other routines.

Notes

  • There are many pitfalls in using functions returning references, however there are situations where this may be useful or useful.
  • Modern programmers use pointers or smart pointers instead of returning by & reference. Pointers are also references with more intuitive tricks for references.

Common Errors

  • Putting & at the wrong place and trying to return non-static or constants as references are common mistakes people do.


Suggested Filename(s): fn-ref-return.cpp, ref-ret.cpp



Share

Created: 18-Jan-2018 00:57 | Updated: 18-Jan-2018 01:22|