C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Structures in C

Returning structure from function

C Program: Returning structure from function

C

#include <stdio.h>

 

// Structure Definition

struct Employee {

    int id;

    char name[50];

    float salary;

};

 

// Function Declaration

struct Employee getEmployee();  // Function returns a structure

void displayEmployee(struct Employee e); // Function takes structure as argument

 

int main() {

    struct Employee emp;

 

    // Function call to get employee details

    emp = getEmployee();

 

    // Display the employee details

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

    displayEmployee(emp);

 

    return 0;

}

 

// Function Definition: Returns a structure

struct Employee getEmployee() {

    struct Employee e;

 

    printf("Enter Employee ID: ");

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

 

    printf("Enter Employee Name: ");

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

 

    printf("Enter Employee Salary: ");

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

 

    return e; // returning structure variable

}

 

// Function to display employee details

void displayEmployee(struct Employee e) {

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

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

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

}

Output

 
OUTPUT 1 :
Enter Employee ID: 201
Enter Employee Name: Sita Verma
Enter Employee Salary: 52000

--- Employee Details ---
ID      : 201
Name    : Sita Verma
Salary  : 52000.00

Explanation

Concept

Description

struct Employee getEmployee()

Function that returns a structure of type Employee.

emp = getEmployee();

Structure returned from the function and stored in variable emp.

return e;

Returns an entire structure, not just a single value.

displayEmployee(emp)

Function takes structure as a parameter.