Structure and Function | C++ Structure and Function - Learn C++ - C++ Tutorial - C++ programming
![c++-structure-and-function](https://wikitechy.com/tutorials/c++/img/c++-images/c++-structure-and-function.gif)
Learn c++ - c++ tutorial - c++-structure-and-function - c++ examples - c++ programs
Structure And Function in C++
- Structure is a collection of variables under a single variable.
- Structure variables can be passed to a function and returned in a similar way as normal argument.
- A function is a group of statements that together perform a task.
- Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions. You can divide up your code into separate functions.
![learn c++ tutorials - structure and functions](https://wikitechy.com/tutorials/c++/img/c++-images/pass-by-reference-vs-pass-by-value.gif)
learn c++ tutorials - structure and functions Example
Learn C++ , C++ Tutorial , C++ programming - C++ Language -Cplusplus
Passing structure to function in C++
![pass return object c++](https://wikitechy.com/tutorials/c++/img\c++-images\pass-return-object-c++.jpg)
- A structure variable can be passed to a function in similar way as normal argument.
- When an element of a structure is passed to a function, you are actually passing the values of that element to the function. Therefore, it is just like passing a simple variable (unless, of course, that element is complex such as an array of character). Consider this example:
Example 1: C++ Structure and Function
#include <iostream>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
void displayData(Person); // Function declaration
int main()
{
Person p;
cout << "Enter Full name: ";
cin.get(p.name, 50);
cout << "Enter age: ";
cin >> p.age;
cout << "Enter salary: ";
cin >> p.salary;
// Function call with structure variable as an argument
displayData(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
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 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 are displayed from this function.