How to pass a structure to a function in C++
COS1511 - Introduction To Programming I · Learning C++
How to pass a structure to a function in C++
In C++, a structure (or struct) is a user-defined data type that allows you to combine data items of different kinds. You can create a structure to group related variables together. When you want to use a structure in a function, you can pass it as a parameter. This allows the function to access and manipulate the structure's data.
Defining a Structure
To define a structure, you use the struct keyword followed by the structure name and its members. Here is an example:
struct Person { int age; float height; char name[50];};In this example, we have defined a structure called Person that contains three members: age (an integer), height (a float), and name (an array of characters).
Passing a Structure to a Function
To pass a structure to a function, you can use either pass by value or pass by reference. Each method has its own use cases.
Pass by Value
When you pass a structure by value, a copy of the structure is made. Changes made to the copy do not affect the original structure. Here is how to do it:
void displayPerson(Person p) { cout << "Name: " << p.name << endl; cout << "Age: " << p.age << endl; cout << "Height: " << p.height << endl;} In this function, displayPerson, we take a Person structure as a parameter. We can then access its members and display them. To call this function, you would do the following:
Person person1; strcpy(person1.name, "John"); person1.age = 30; person1.height = 1.75; displayPerson(person1);In this example, we create a Person object called person1, set its members, and then pass it to the displayPerson function.
Watch out: When passing by value, the original structure will not be modified. If you need to change the original structure, use pass by reference instead.
Pass by Reference
Passing a structure by reference allows the function to modify the original structure. You do this by using the & symbol in the function parameter. Here is an example:
void updatePerson(Person &p) { p.age += 1; strcpy(p.name, "Updated Name");}In this function, updatePerson, we take a reference to a Person structure. This means that any changes made to p will affect the original structure.
To call this function, you would do the following:
updatePerson(person1);After calling updatePerson, the age of person1 will be increased by 1, and the name will be changed to