Structure and Function in C++
Structure and Function in C++
Structure variables is pass to a function and return in a same way as regular parameter
Passing structure to function in C++
A structure variable is passed to a function in same way as normal argument.
Program of passing structure to function in C++
#include <iostream> using namespace std; struct Emp { char name[50]; int age; float salary; }; void displayData(Emp); // Function declaration int main() { Emp e; cout << "Enter name: "; cin.get(e.name, 50); cout << "Enter age: "; cin >> e.age; cout << "Enter salary: "; cin >> e.salary; displayData(e); return 0; } void displayData(Emp e) { cout << "\n Information." << endl; cout << "Name: " << e.name << endl; cout <<"Age: " << e.age << endl; cout << "Salary: " << e.salary; }
Output
Enter Full name: John Jain Enter age: 50 Enter salary: 30000 Information. Name: John Jain Age: 50 Salary: 30000
Returning structure from function in C++
Program of Returning structure from function in C++
#include <iostream> using namespace std; struct Student{ char stuName[50]; int stuRollNo; int stuAge; }; Student getStudentInfo(); void printStudentInfo(Student); int main(){ Student s; s = getStudentInfo(); printStudentInfo(s); return 0; } Student getStudentInfo(){ Student s; cout<<"Enter Student Name: "; cin.getline(s.stuName, 30); cout<<"Enter Student Roll No: "; cin>>s.stuRollNo; cout<<"Enter Student Age: "; cin>>s.stuAge; return s; } void printStudentInfo(Student s){ cout<<"Student Record:"<<endl; cout<<"Name: "<<s.stuName<<endl; cout<<"Roll No: "<<s.stuRollNo<<endl; cout<<"Age: "<<s.stuAge; }
Output
Enter Student Name: Kamya Singh Enter Student Roll No: 667382 Enter Student Age: 20 Student Record: Name: Kamya Singh Roll No: 667382 Age: 20
Read more, Structures in C++