Structures and Functions in c++

Structures and Functions in c++

n this article, you'll find relevant examples to pass structures as an argument to a function, and use them in your program.

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


Comments

Popular posts from this blog

C++ Program to Store and Display Information Using Structure