C++ Structure and Function



Structure variables can be passed to a function and returned in a similar way as normal arguments.

Passing structure to function in C++

A structure variable can be passed to a function in similar way as normal argument. Consider this example:

Example 1: C++ Structure and Function

  1. #include <iostream>
  2. using namespace std;
  3. struct Person
  4. {
  5. char name[50];
  6. int age;
  7. float salary;
  8. };
  9. void displayData(Person); // Function declaration
  10. int main()
  11. {
  12. Person p;
  13. cout << "Enter Full name: ";
  14. cin.get(p.name, 50);
  15. cout << "Enter age: ";
  16. cin >> p.age;
  17. cout << "Enter salary: ";
  18. cin >> p.salary;
  19. // Function call with structure variable as an argument
  20. displayData(p);
  21. return 0;
  22. }
  23. void displayData(Person p)
  24. {
  25. cout << "\nDisplaying Information." << endl;
  26. cout << "Name: " << p.name << endl;
  27. cout <<"Age: " << p.age << endl;
  28. cout << "Salary: " << p.salary;
  29. }
Output
Enter Full name: Bill Jobs
Enter age: 55
Enter salary: 34233.4

Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4
In this program, user is asked to enter the nameage and salary of a Person inside main() function.
Then, the structure variable p is to passed to a function using.
displayData(p);
The return type of displayData() is void and a single argument of type structure Person is passed.
Then the members of structure p is displayed from this function.

Example 2: Returning structure from function in C++

  1. #include <iostream>
  2. using namespace std;
  3. struct Person {
  4. char name[50];
  5. int age;
  6. float salary;
  7. };
  8. Person getData(Person);
  9. void displayData(Person);
  10. int main()
  11. {
  12. Person p;
  13. p = getData(p);
  14. displayData(p);
  15. return 0;
  16. }
  17. Person getData(Person p) {
  18. cout << "Enter Full name: ";
  19. cin.get(p.name, 50);
  20. cout << "Enter age: ";
  21. cin >> p.age;
  22. cout << "Enter salary: ";
  23. cin >> p.salary;
  24. return p;
  25. }
  26. void displayData(Person p)
  27. The output of this program is same as program above.
    In this program, the structure variable p of type structure Person is defined under main() function.
    The structure variable p is passed to getData() function which takes input from user which is then returned to main function.
    p = getData(p); 
    Note: The value of all members of a structure variable can be assigned to another structure using assignment operator = if both structure variables are of same type. You don't need to manually assign each members.
    Then the structure variable p is passed to displayData() function, which displays the information.

Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website