Defining structure outside the function

If we define the structure inside any function, then the structure variable declared to the structure datatype is considered as a local structure variable and if we define structure outside the function, then its structure variable is considered as a global structure variable.

You know the difference between global and local variables

Global variables are those which are declared globally at the top of the program after the header file and can be used anywhere in the entire program.

Local variables are those which are declared in a particular function and those variables can be used only inside that function or block of code.

Demo program

#include<stdio.h>

struct student
{
 int roll_no;
 char name[10];
}stu1={10,"pravin"};

int main()
{ 
  struct student stu2;
  printf("rollno %d\n",stu1.rollno);
  printf("name %s \n",stu1.name);

  printf("Enter the rollno and name for  second student\n");

  scanf("%d  %s", &roll_no,name);
  printf("Print the rollno and name of second student");
 
  printf("rollno=%d  name=%s",roll_no,name);
  return 0;
}

 Output:

Defining-structure-outside-function-c
Explanation: 

We defined the structure outside the main function.  

We declared and initialized the details of the first student outside the main function and printed it inside the main function.  

We declared the second structure variable “stu2” inside the main function. 

The conclusion is when we define the structure outside the function, we can declare, print, initialize, or modify its variable anywhere in the program.

 

also, see:

structure in c