Using function return by reference to modify a global array
A program that neatly modifies a global array by using the function return by reference technique.
Learning Objectives
- Use of function returning reference in case of pointing to each array index, so that the values can be intuitively modified.
Source Code
|
Run Output
Code Understanding
int& modifyga(int); This function takes an integer input and return the reference to the place where modified value of input is stored.
int ga[]={10,20,30,40,50};
This is global array declared and initialised before the main routine which will be modified.
for(int i=0;i<5;++i) //Loop to use the modification function many times.
modifyga(i)=ga[i]+1;
Here left hand side is showing a function as it is a reference returning function. In each iteration the current value of global array ga will be modified to a new value which adds 1 to previous value.
for(int i=0;i<5;++i) cout<<ga[i]<<” “;
This is final array values printing loop
int& modifyga(int i) { return ga[i]; }
This function returns the reference to an array based on the index passed to it.
Notes
- In this function returning reference provide a quite intuitive way of writing array modification with common rules.
- The same method can used to make other kind of modifications, say multiplying each value by 2, squaring each value and many similar things.
- Such functions should be written for global/static scope variables or arrays.
Suggested Filename(s): fnref-modify-array.cpp, frefarr.cpp
sunmitra| Created: 18-Jan-2018 | Updated: 18-Jan-2018|