How to pass or return a structure to/from a Function in C/C++?
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.
How to pass structure as an argument to the functions?
Passing of structure to the function can be done in two ways:
- By passing all the elements to the function individually.
- By passing the entire structure to the function.
In this article, entire structure is passed to the function. This can be done using call by reference as well as call by value method.
Examples 1: Using Call By Value Method
#include <bits/stdc++.h>
using namespace std;
struct Distance {
int kilometer;
int meter;
};
void TotalDistance(Distance d1, Distance d2)
{
Distance d;
d.kilometer = d1.kilometer
+ d2.kilometer
+ (d1.meter + d2.meter)
/ 1000;
d.meter = (d1.meter + d2.meter) % 1000;
cout << "Total distance:" ;
cout << "kilometer: "
<< d.kilometer << endl;
cout << "meter: " << d.meter
<< endl;
}
void initializeFunction()
{
Distance Distance1, Distance2;
Distance1.kilometer = 10;
Distance1.meter = 455;
Distance2.kilometer = 9;
Distance2.meter = 745;
TotalDistance(Distance1, Distance2);
}
int main()
{
initializeFunction();
return 0;
}
|
Output:
Total distance:kilometer: 20
meter: 200
Examples 2: Using Call By Reference Method
#include <bits/stdc++.h>
using namespace std;
struct number {
int n;
};
void increment(number& n2)
{
n2.n++;
}
void initializeFunction()
{
number n1;
n1.n = 10;
cout << " number before calling "
<< "increment function:"
<< n1.n << endl;
increment(n1);
cout << "number after calling"
<< " increment function:" << n1.n;
}
int main()
{
initializeFunction();
return 0;
}
|
Output:
number before calling increment function:10
number after calling increment function:11
How to return a structure from the functions?
To return a structure from a function the return type should be a structure only.
Examples:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct Employee {
int Id;
string Name;
};
Employee data(Employee E)
{
E.Id = 45;
E.Name = "aman" ;
return (E);
}
int main()
{
Employee Emp;
Emp = data(Emp);
cout << "Employee Id: " << Emp.Id;
cout << "\nEmployee Name: " << Emp.Name;
return 0;
}
|
Output:
Employee Id: 45
Employee Name: aman
Last Updated :
16 Dec, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...