Write a structure in local scope program using C language

CServer Side ProgrammingProgramming

Structure is a collection of different datatype variables, grouped together under a single name.

Features of structure

The features of structure are explained below −

  • It is possible to copy the contents of all structure elements of different datatypes to another structure variable of its type by using an assignment operator.

  • For handling complex datatypes, it is better to create a structure within an another structure, which is called as the nested structures.

  • It is possible to pass an entire structure, individual elements of a structure and an address of structure to a function.

  • It is also possible to create the structure pointers.

Declaration of structures

The general form of structure declaration is as follows −

datatype member1;
struct tagname{
   datatype member2;
   datatype member n;
};

Here, struct is the keyword.

   tagname specifies name of structure.

   member1, member2 are the data items.

For example,

struct book{
   int pages;
   char author [30];
   float price;
};

Example

Following is the C program for structure in local scope −

 Live Demo

#include<stdio.h>
struct{
   char name[20];
   int age;
   int salary;
   char add[30];
}emp1,emp2;
int manager(){
   struct{
      char name[20];
      int age;
      int salary;
      char add[50];
   }manager ;
manager.age=27;
if(manager.age>30)
   manager.salary=65000;
else
   manager.salary=55000;
   return manager.salary;
}
int main(){
   printf("enter the name of emp1:");
   //gets(emp1.name);
   scanf("%s",emp1.name);
   printf("\nenter the add of emp1:");
   scanf("%s",emp1.add);
   printf("\nenter the salary of emp1:");
   scanf("%d",&emp1.salary);
   printf("\nenter the name of emp2:");
   // gets(emp2.name);
   scanf("%s",emp2.name);
   printf("\nenter the add of emp2:");
   scanf("%s",emp2.add);
   printf("\nenter the salary of emp2:");
   scanf("%d",&emp2.salary);
   printf("\nemp1 salary is %d",emp1.salary);
   printf("\nemp2 salary is %d",emp2.salary);
   printf("\nmanager salary is %d",manager());
   return 0;
}

Output

When the above program is executed, it produces the following result −

enter the name of emp1:hari
enter the add of emp1:hyderabad
enter the salary of emp1:4000
enter the name of emp2:lucky
enter the add of emp2:chennai
enter the salary of emp2:5000
emp1 salary is 4000
emp2 salary is 5000
manager salary is 55000
raja
Published on 09-Mar-2021 13:19:23
Advertisements