C++ Structure and Function

We can pass structure variables to a function and return it from a function in a similar way as normal arguments.


Passing Structure to Function in C++

A structure variable can be passed to a function just like any other argument.

Consider this example:

#include <iostream>
#include <string>
using namespace std;

struct Person {
    string name;
    int age;
    float salary;
};

// declare function with
// structure variable type as an argument
void display_data(const Person&);

int main() {
    Person p;

    p.name = "John Doe";
    p.age = 22;
    p.salary = 145000;

    // function call with 
    // structure variable as an argument
    display_data(p);

    return 0;
}

void display_data(const Person& p) {
    cout << "Name: " << p.name << endl;
    cout << "Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}

Output

Name: John
Age: 22
Salary: 145000

In this program, we passed the structure variable p by reference to the function display_data() to display the members of p.


Return Structure From Function in C++

We can also return a structure variable from a function.

Let's look at an example.

#include <iostream>
#include <string>
using namespace std;

// define structure
struct Person {
    string name;
    int age;
    float salary;
};

// declare functions
Person get_data();
void display_data(const Person&);

int main() {

    Person p = get_data();
    display_data(p);

    return 0;
}

// define function to return structure variable
Person get_data() {

    Person p;
    
    cout << "Enter full name: ";
    getline(cin, p.name);

    cout << "Enter age: ";
    cin >> p.age;

    cout << "Enter salary: ";
    cin >> p.salary;
    
    // return structure variable
    return p;
}

// define function to take
// structure variable as an argument
void display_data(const Person& p) {
    cout << "\nDisplaying Information." << endl;
    cout << "Name: " << p.name << endl;
    cout << "Age: " << p.age << endl;
    cout << "Salary: " << p.salary;
}

Output

Enter full name: John Doe
Enter age: 22
Enter salary: 145000

Displaying Information.
Name: John Doe
Age: 22
Salary: 145000

In this program, we took user input for the structure variable p in the get_data() function and returned it.

Then we passed the structure variable p to display_data() function by reference, which displays the information.


Also Read:

Did you find this article helpful?