In previous tutorial we learnt about structures.
In this tutorial, we will learn we will learn how to pass structures as an argument to the function and how to return the structure from the function.
Here we have a function printStudentInfo()
which takes structure Student
as an
argument and prints the details of student using structure varaible. The important point
to note here is that you should always declare the structure before function declarations,
otherwise you will get compilation error.
Example:
#include <iostream> using namespace std; struct Student{ char stuName[30]; int stuRollNo; int stuAge; }; voidprintStudentInfo(Student); int main(){ 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; printStudentInfo(s); return 0; } void printStudentInfo(Students) { cout << "StudentRecord: " << endl; cout << "Name: "<< s.stuName << endl; cout << "RollNo: "<< s.stuRollNo << endl; cout << "Age: " << s.stuAge; }p Output :
Enter Student Name: Rohit Enter Student Roll No: 727344 Enter Student Age: 20 StudentRecord: Name: Rohit Roll No: 727344 Age: 20
The struct
keyword is used to createa structure. The general syntax to create a
structure is as shown below:
struct structure Name{ member1; member2; member3; . . . memberN; };
Example :
int roll; int age; int marks; void print Details() { cout << "Roll = " << roll << "\n"; cout << "Age = " << age << "\n"; cout << "Marks = " << marks; }
In the above structure, the data members are three integer
variables to store roll number, age and marks of any student and
the member function is printDetails()
which is printing all of the
above details of any student.
A structure variable can either be declared with structure declaration or as a separate declaration like basic types.
struct Point { int x, y; }p1; struct Point { int x, y; }; int main() { struct Point p1; }
Note: In C++, the struct
keyword is optional before in
declaration of a variable. In C, it is mandatory.
Structure members cannot be initialized with declaration. For example, the following C program fails in compilation.
But is considered correct in C++11 and above.
struct Point { int x = 0; // COMPILER ERROR: cannot initialize members here int y = 0; // COMPILER ERROR: cannot initialize members here };
The reason for above error is simple, when a data type is declared, no memory is allocated for it. Memory is allocated only when variables are created.
Structure members can be initialized using curly braces
{}
. For example, following is a valid initialization.
struct Point { int x, y; }; int main() { struct Point p1 = {0, 1}; }
Structure members are accessed using dot (.) operator.
#include <iostream> using namespace std; struct Point { int x, y; }; int main() { struct Point p1 = {0, 1}; p1.x = 20; cout << "x = " << p1.x << ",y = " << p1.y; return 0; }
Output:
x = 10, y = 20