Jan 2, 2016

C Programming #55: Structure declaration and definition

Declaration/Definition of structure type/structure variable can be done in several ways. This article would like to explain them in detail.

As you already know

  1. Declaration will identity the data type (mentioning the blue print of type).
  2. Definition will allocate memory to variable.

Hence it is always "Declaring a type and defining a variable".



Declaration and definition could be done separately which is illustrated in the below example

Declaration of type "struct student"

struct student {
   char name[20];
   int age;
   int class;
}; 

Definition of variable (Note it also includes initialization)

struct student a = {"Ram", 7, 2};

Now both declaration and definition could be combined together as follows

struct student {
   char name[20];
   int age;
   int class;
}a = {"Ram", 7, 2};

This not only does declare a new type "struct student" but also defines variable a. Two avoid in definition mentioning struct every time generally when declaring a structure a typedef is used.

typedef struct student {
   char name[20];
   int age;
   int class;
}student_t; 

Now definition could be done in two ways show below

  1. struct student a;
  2. student_t a;


Since second definition doesn't involve using struct keyword; it is generally preferred. Also such typdefs have _t suffixed to remind programmer that is some typedef hiding a declaration. C allows un-named definition of structure variable

struct {
   char name[20];
   int age;
   int class;
}a = {"Ram", 7, 2};

Here a is unnamed structure variable with member variable name, age and class as member variable.

Links

Next Article - C Programming #56: Structure - forward declaration
Previous Article - C Programming #54: Structure pointer
All Article - C Programming

No comments :

Post a Comment