English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Structure and Function

In this article, you will find relevant examples of passing a structure as a parameter to a function and using them in the program.

You can passthe structurevariables passed toFunctionand return it in a way similar to regular variables.

passing a structure to C ++the function

You can pass a structure variable to a function like a regular parameter. Consider the following example:

Example1: C ++Structure and Function

#include <iostream>
using namespace std;
struct Person
{
    char name[50];
    int age;
    float salary;
};
void displayData(Person);   // Function Declaration
int main()
{
    Person p;
    cout << "Enter Name: ";
    cin.get(p.name, 50);
    cout << "Enter Age: ";
    cin >> p.age;
    cout << "Enter Salary: ";
    cin >> p.salary;
    // Function Call, Structure Variable as Parameter
    displayData(p);
    return 0;
}
void displayData(Person p)
{
    cout << "Display Information" << endl;
    cout << "Name: " << p.name << endl;
    cout << "Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}

Output Result

Enter Name: Bill Jobs
Enter Age: 55
Enter Salary: 34233.4
Display Information
Name: Bill Jobs
Age: 55
Salary: 34233.4

In this program, it is required to input a person's name, age, and salary in the main() function.

Then, pass the structure variable p to the function.

displayData(p);

The return type of displayData() is void and it passes a parameter of type structure Person.

Then display the members of structure p from this function.

Example2from C ++the function returns a structure

#include <iostream>
using namespace std;
struct Person {
    char name[50];
    int age;
    float salary;
};
Person getData(Person); 
void displayData(Person); 
int main()
{
    Person p;
    p = getData(p);   
    displayData(p);
    return 0;
}
Person getData(Person p) {
    cout << "Enter Name: ";
    cin.get(p.name, 50);
    cout << "Enter Age: ";
    cin >> p.age;
    cout << "Enter Salary: ";
    cin >> p.salary;
    return p;
}
void displayData(Person p)
{
    cout << "Display Information" << endl;
    cout << "Name: " << p.name << endl;
    cout << "Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}

The output of this program is the same as the above program.

In this program, a structure variable p of type Person is defined in the main() function.

The structure variable p is passed to the getData() function, which takes input from the user and then returns it to the (main) main function.

p = getData(p);

Note:If two structure variables have the same type, you can use the assignment operatorAssignment operator (=)The values of all members of the structure variable are assigned to another structure. You do not need to manually allocate each member.

Then pass the structure variable p to the displayData() function, which displays the information.