Home » Learn C++ » Passing Structure to Functions

Passing Structure to Functions

Passing Structures to Functions:

            The structures can also be passed as arguments to a function. If a structure is to be passed to a function, then it must be defined before the declaration of the function that uses the structure type data as argument.
The program example given below explains the use of structure type data as argument of a function.

 

Program:

           

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
struct xyz

{
char name [15];
int age;

};
main ( )

{
xyz s1;
void rec (xyz);
clrscr ( );
cout<< “Enter name ?” ;
gets (s1.name);
cout << “Enter age ?” ;

cin >> s1.age;

rec (s1);

cout << “Ok”;

}

void rec (xyz fs)

{

cout << “Name =” << fs.name << endl;

cout << “Age =” << fs.age << endl;

}

 

            The variable s1 is declared as structure type (i.e. xyz) inside the main function and the function “rec” is declared after this. The function “rec” uses an argument of type “xyz”, i.e. of structure type. The function “rec” is called by passing the structure variable s1 to function definition.

            In function definition the variable “fs” of type “xyz” receives the data of s1 and the same is printed on the screen. An array of structure type can also he passed as argument to a function in the similar way as any other array is passed as argument.

Other Topics

comment closed

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Copyright © 2010 Information Village. All rights reserved.