B05 - C++ Structure and Function
B05 - C++ Structure and Function
struct Person {
char name[50];
int age;
float salary;
};
int main() {
Person p;
return 0;
}
void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
Output
Displaying Information.
Name: Bill Jobs
Age: 55
Salary: 34233.4
In this program, user is asked to enter the name , age 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.
struct Person {
char name[50];
int age;
float salary;
};
Person getData(Person);
void displayData(Person);
int main() {
Person p, temp;
temp = getData(p);
p = temp;
displayData(p);
return 0;
}
Person getData(Person p) {
cout << "Enter Full name: ";
cin.get(p.name, 50);
return p;
}
void displayData(Person p) {
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p.name << endl;
cout <<"Age: " << p.age << endl;
cout << "Salary: " << p.salary;
}
temp = getData(p);
p = temp;
Then the structure variable p is passed to displayData() function, which displays
the information.
Note: We don't really need to use the temp variable for most compilers and C+
+ versions. Instead, we can simply use the following code:
p = getData(p);