# Structure and Functions

0 Ioannis Kastrinakis November 13, 2020

Like an ordinary variable, a structure variable also can be passed to a function. we may either pass individual structure elements or the entire structure.

A structure member can be treated just like any other variable of that type. For example, an integer member of the structure can be treated just as an integer. Thus structure members can be passed to functions like ordinary variables.

## Passing structure member to functions

``````#include <stdio.h>

void disp(char empName[], int id, float sal){
printf("\nName\t\tID\t\tSalary\n");
printf("\n%s\t\t%d\t\t%.1f", empName, id, sal);
}

int main()
{
struct employee{
char name[20];
int id;
float salary;
}

struct employee emp;

printf("Employee Name : ");
scanf("%s", emp.name);

printf("\nEmployee ID : ");
scanf("%d", &emp.id);

printf("\nEmployee Salary : ");
scanf("%f", &emp.salary);

printf("\n\nThe Entire Information of the employee is\n\n");
disp(emp.name, emp.id, emp.salary);
}``````

The output of the above program is:

``````Employee Name : Suresh
Employee ID : 20
Employee Salary : 20000

The Entire Information of the employee is
Name        ID      Salary
Suresh      20      20000``````

## Passing whole structure to functions

It is possible to send entire structures to functions as arguments in the function call. The structure variable is treated as an ordinary variable.

``````#include <stdio.h>

struct employee{
char name[20];
int id;
float salary;
}

void disp(struct employee e){
printf("\nName\t\tID\t\tSalary\n");
printf("\n%s\t\t%d\t\t%.1f", e.name, e.id, e.salary);
}

int main()
{

struct employee emp;

printf("Employee Name : ");
scanf("%s", emp.name);

printf("\nEmployee ID : ");
scanf("%d", &emp.id);

printf("\nEmployee Salary : ");
scanf("%f", &emp.salary);

printf("\n\nThe Entire Information of the employee is\n\n");
disp(emp);
}``````

The output of the above program is:

``````Employee Name : Suresh
Employee ID : 20
Employee Salary : 20000

The Entire Information of the employee is
Name        ID      Salary
Suresh      20      20000``````

Here, Output is similar to the previous program in which individual elements were passed to functions. But the difference is that the whole structure has been passed in this example.

When the structure variable emp of type employee is passed in the function call, then the type of formal argument in the function definition must be of type Employee. Thus, the structure Employee must be used in both in main() function and user-defined function disp(). Thus, this structure has been declared global i.e. outside of the main() function.