Passing Structure variables to a function – Computer Sir Ki Class

Code Learning #CPP#2955

## 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

 #include using namespace std; const double PI=3.1416; struct Circle { int x,y; float rad; }; double CirArea(float r) { return PI*r*r; } float CirTop(float &r,int &yc) { return yc+r; } int main() { Circle c1={10,10,5.5}; cout<<"Area of given circle : " <

## Run Output

Area of given circle : 95.0334
Top point of given circle : 15.5

## 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

sunmitra| Created: 23-Jan-2018 | Updated: 23-Jan-2018|

×