Ads block

Banner 728x90px

Declaring Structure Variables

In the previous section we have only created a template or format of a structure, the actual use of structures will be when we declare variables based on this format. To use of structures we have to declare structure variables. We can declare structure variables in two ways-

  • With structure definition
  • Using the structure tag

1) With Structure Definition

struct student{
                 char name[20];
                 int roll_no;
                 float marks;
              }stu1, stu2, stu3;

Here stu1, stu2 and stu3 are variables of type struct srudent. We can define the structure template without the use of tagname, it is optional. What will happen if we not use tagname during structure defining? It is discussed below.

struct {
           char name[20];
           int roll_no;
           float marks;
       }stu1, stu2, stu3;

If we declare variables in this way, then we'll not able to declare other variables of this structure type anywhere else in the program nor can we send these structure variables to functions.

If a need arises to declare a variable of this type in the program then we'll have to write the whole template again. So although the tagname is optional but it is better to specify a tagname for the structure.


2) Using Structure Tag

We can also declare structure variables using structure tag. This is a another way to declare structure variables, and can be written as-

struct student{
               char name[20];
               int roll_no;
               float marks;
              };
struct student stu1, stu2;
struct student stu3;

Here stu1, stu2 and stu3 are structure variables that are declared using the structure tag student. Now after declaring a structure variables, it reserves space in memory. Each structure variables declared to be of type struct student.
The compiler will reserve space for each variable sufficient to hold all the members.