C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures in C

Passing structure to function

C Program: Passing structure to function

C

#include <stdio.h>

 

// Structure definition

struct Employee {

    int id;

    char name[50];

    float salary;

};

 

// Function Declaration

void displayEmployee(struct Employee e);         // Pass by value

void updateSalary(struct Employee *e, float inc); // Pass by reference

 

int main() {

    struct Employee emp;

 

    // Input employee details

    printf("Enter Employee ID: ");

    scanf("%d", &emp.id);

 

    printf("Enter Employee Name: ");

    scanf(" %[^\n]", emp.name);

 

    printf("Enter Employee Salary: ");

    scanf("%f", &emp.salary);

 

    printf("\n--- Employee Details (Before Increment) ---\n");

    displayEmployee(emp);

 

    // Call function by reference to update salary

    updateSalary(&emp, 5000.0);

 

    printf("\n--- Employee Details (After Increment) ---\n");

    displayEmployee(emp);

 

    return 0;

}

 

// Function Definition: Pass structure by value

void displayEmployee(struct Employee e) {

    printf("ID      : %d\n", e.id);

    printf("Name    : %s\n", e.name);

    printf("Salary  : %.2f\n", e.salary);

}

 

// Function Definition: Pass structure by reference

void updateSalary(struct Employee *e, float inc) {

    e->salary += inc;

}

Output

 
OUTPUT :
Enter Employee ID: 101
Enter Employee Name: Ramesh Kumar
Enter Employee Salary: 45000

--- Employee Details (Before Increment) ---
ID      : 101
Name    : Ramesh Kumar
Salary  : 45000.00

--- Employee Details (After Increment) ---
ID      : 101
Name    : Ramesh Kumar
Salary  : 50000.00

Explanation

Concept

Description

struct Employee e

Defines structure for employee info.

displayEmployee(emp)

Structure passed by value — copy of emp.

updateSalary(&emp, 5000.0)

Structure passed by reference using pointer — updates original data.

e->salary

Arrow operator used to access structure members through pointer.