Passing Structure variables to a function
Demonstration of how structure variables can be passed to function as pass-by-value or as pass-by-reference method
Learning Objectives
- To pass member variables of a structure to a function using pass by value method and by using pass by reference method.
Source Code
|
|
Run Output
Code Understanding
const double PI=3.1416; //This will be used in circle formulas
struct Circle { int x,y; float rad;};
A structure named Circle with variables x and y as circle center co-ordinates and rad as its radius.
double CirArea(float r) { return PI*r*r; }
This is a function definition which can return area of circle, Here radius is passed as a value and area is also returned as value in double type.
float CirTop(float &r,int &yc) {return yc+r;}
This function definition has arguments passed as reference for &r for radius and &yc as y co-ordinate of top point of circle.
Circle c1={10,10,5.5}; //Instance c1 of Circle structure has been initialised with x=10, y=10, rad=5.5;
cout<<“Area of given circle : ” <<CirArea(c1.rad)<<endl;
Area is printed here. Note that function has been called in the cout chain with structure variable directly passed to it as a value.
float r=c1.rad; //New variable r created from the initialised value of instance c1.
int yc=c1.y; //New variable yc created from the initialised value of instance c1.
Since r and yc are supposed to be passed by reference so we have created a copy in r and yc.
cout<<“Top point of given circle : ” <<CirTop(r,yc)<<endl;
The top point of circle is calculated by calling the function where variables are passed by reference.
Notes
- Since structures usually contain publicly accessible data by all functions, one must take care that all the variable passed by reference will be accessible to other functions also if structure members are passed directly, so it is always advisable to make a copy of variables before passing them to functions as reference.
Suggested Filename(s): stru-var-pass.cpp,stvarpas.cpp
Created: 23-Jan-2018 16:45 | Updated: 23-Jan-2018 17:05|
