Passing structure to a function pass-by-value – Computer Sir Ki Class

Code Learning #CPP#2969

## Passing structure to a function pass-by-value

A program to demonstrate passing of structure to a function using pass by value method,

## Learning Objectives

• Learning to pass structure to a function using the pass by value in the argument of the function.

## Source Code

 #include using namespace std; struct Sale { int ItemID; int qty; float uprice; }; float price(Sale s) { return s.qty*s.uprice; } int main() { Sale s1={1,7,25.0},s2={1,3,15.0}; cout<<"ItemIDtQtytUPtPrice"<

## Run Output

``````ItemID  Qty     UP      Price
-----------------------------
1       7       25      175
1       3       15      45
``````

## Code Understanding

struct Sale { int ItemID; int qty; float uprice;};
Structure Sale is declared with some predefined variables.

float price(Sale s) { return s.qty*s.uprice; }
This is the function where the whole structure is passed as its argument. This function returns the price based on multiplication of s.qty and s.uprice. The Sale s argument creates a local instance of structure which can be used in this function body only. This is pass by value technique.

Sale s1={1,7,25.0},s2={1,3,15.0};
Two instances s1 and s2 are declared and initialised with the given values. The value type and order should match the declaration given in the structure Sale.

cout<<“ItemIDtQtytUPtPrice”<<endl;
cout<<“—————————–“<<endl;
These lines to print heading lines before the data.

cout<<s1.ItemID<<“t”<<s1.qty<<“t”<<s1.uprice<<“t”<<price(s1)<<endl;
This line prints the data for instance s1 of the structure. Notice the function call price(s1) where the structure is directly passed to the function

cout<<s2.ItemID<<“t”<<s2.qty<<“t”<<s2.uprice<<“t”<<price(s2)<<endl;
This line is for another instance data printing.

## Notes

• Structure passing by value works exactly like single variable passing, but it has a clear advantage of passing many variables of different data types together.
• Although structure instance passed as argument is local to the function only, it is still recommended to use a different name from the other instance names. This is advisable as mostly structure have publicly available instances.

Suggested Filename(s): struc2fnv.cpp

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

×