The relation of structure and function in C++ is that just like any other argument passed in a function, a structure can also be passed.
Passing structure to function in C++
We can pass and access the structure to function as an argument in a program. It is similar to the way we pass a normal argument to a function. And it is also returned from a function just like any other argument.
Let us understand through an example.
#include<iostream>
#include <cstring>
using namespace std;
struct Student
{
char name[50];
int roll;
};
void display(struct Student s); // Function declaration
int main()
{
struct Student s;
strcpy(s.name, "John Mathers");
s.roll = 32;
display(s);
return 0;
}
void display(struct Student s)
{
cout << "Person Name: " << s.name<<endl;
cout << "Person Roll: " << s.roll;
}
Output:
Person Name: John Mathers
Person Roll: 32
Returning structure from function in C++
#include<iostream>
#include <cstring>
using namespace std;
struct Student
{
char name[50];
int roll;
};
// Function declaration
Student returnInfo(Student);
void display(struct Student s);
int main()
{
Student s;
s = returnInfo(s);
display(s);
return 0;
}
Student returnInfo(Student s)
{
strcpy(s.name, "John Mathers");
s.roll = 32;
return s;
}
void display(Student s)
{
cout << "Person Name: " << s.name<<endl;
cout << "Person Roll: " << s.roll;
}
The output of this program is the same as the output of the above program.
In this program, the structure variable s stores the returned value from returnInfo() function where value is provided to structure members (s = returnInfo(s);).
After that, the s is passed to display() function where the information os student is displayed.