In C++, we can pass a structure variable to a function as argument like we pass any other variable to a function. Structure variable is passed using call by value. To take a structure variable as argument, function must declare a structure argument in it's declaration. Any change in the value of formal parameter inside function body, will not affect the value of actual parameter.
For Example :struct employee { char name[100]; int age; float salary; char department[50]; }; void printEmployeeDetails(struct employee emp);
We can also pass address of a structure to a function. In this case, any change in the formal parameter inside function's body will reflect in actual parameter also. To take a structure pointer as parameter a function declare a a structure pointer as it's formal parameter.
void printEmployeeDetails(struct employee *emp);Like any other inbuilt data type, we can also pass individual member of a structure as function argument.
C++ Program to Pass Structure Variable to a Function
#include <iostream> using namespace std; struct employee { char name[100]; int age; float salary; char department[50]; }; // This function takes structure variable as parameter void printEmployeeDetails(struct employee emp){ cout << "\n*** Employee Details ***\n"; cout << "Name : " << emp.name << "\nAge : "<< emp.age << "\nSalary : " << emp.salary << "\nDepartment : "<< emp.department; } // This function takes structure pointer as parameter void printEmployeeDetails(struct employee *emp){ cout << "\n--- Employee Details ---\n"; cout << "Name : " << emp->name << "\nAge : "<< emp->age << "\nSalary : " << emp->salary << "\nDepartment : "<< emp->department; } void printAge(int age){ cout << "\n\nAge = " << age; } int main(){ struct employee manager, *ptr; printf("Enter Name, Age, Salary and Department of Employee\n"); // Assigning data to members of structure variable cin >> manager.name >> manager.age >> manager.salary >> manager.department; // Passing structure variable to function printEmployeeDetails(manager); // Passing address of structure variable to a function printEmployeeDetails(&manager); /* Passing structure member to function */ printAge(manager.age); return 0; }Output
Enter Name, Age, Salary and Department of Employee David 32 98765 SDE *** Employee Details *** Name : David Age : 32 Salary : 98765 Department : SDE --- Employee Details --- Name : David Age : 32 Salary : 98765 Department : SDE Age = 32