Like an
ordinary variable, a structure variable can also be passed to a function.
We may either pass individual structure
elements or the entire structure. Let us take an example in which there is
structure employee that has name, sex and salary as members. These members can
be passed to function to display their value.
Example:
In this example, member
variables are displayed by passing individual elements to a function display().
void display(char name[],char s,
int sal)
{
printf("\nName=%s\tSex=%c\tSalary=%d",name,s,sal);
}
void main()
{
struct employee
{
char name[20];
char sex;
int salary;
};
struct employee e={"abc",'M',10000};
display(e.name,e.sex,e.salary);
/*function call in which each elements are passed individually*/
getch();
}
Another Example:
Let us consider above structure but
pass whole structure variable to function.
struct employee
{
char name[20];
char sex;
int salary;
}; // structure is declared
outside main()
void display(struct employee emp)
{
printf("\nName=%s\tSex=%c\tSalary=%d",emp.name,emp.sex,emp.salary);
}
void main()
{
struct employee e={"abc",'M',10000};
clrscr();
display(e); /* function call*/
getch();
}
Comments
Post a Comment