Table of Contents
Structure with function in C++ language
In this tutorial, we will discuss the concept of Structure with function in C++ language
a structure variable can be passed to a function as an argument
There are two way to pass a function as argument
- passing to a function by value
- passing to a function by reference
passing to a function by value
In this case, The structure object is passed as a function argument to the definition of function. “Structure object” represents the structure’s members and their values.
Program 1
Enter student full name : Jhon mackal Enter student s age : 34 Enter student s marks: 88 Display student details ........................................... student name : Jhon mackal student age : 34 student marks : 88
Passing to function by reference
In this case, the address(reference) of the structure variables are passed as a function argument to the definition of the function.
Program 2
#include <iostream>
#include <conio.h>
using namespace std;
struct student{
int rgNo;
char gender;
int age;
};
void display (student s);
//Declaration of display function with normal reference
void show (student *s);
//Declaration of show function with pointer reference
int main()
{
student anil={1122,'m',26};
display(anil);//Call the display function
show(&anil);//Call the show function
getch();
return 0;
}
void display(student s){
cout<<"Result using display function"<<endl;
//Definition of display function with normal variable
cout<<s.rgNo<<endl;
cout<<s.gender<<endl;
cout<<s.age<<endl<<endl;
}
void show(student *s){
cout<<"Result using show function"<<endl;
//Definition of display function with pointer variable
cout<<s->rgNo<<endl;
cout<<s->gender<<endl;
cout<<s->age<<endl;
}
When the above program is executed, it produces the following results.
This output received pass by value
result using display function 1122 m 26
This output received pass by reference
result using show function 1122 m 26
Related post
