As you already know
- Declaration will identity the data type (mentioning the blue print of type).
- 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
- struct student a;
- 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 declarationPrevious Article - C Programming #54: Structure pointer
All Article - C Programming
No comments :
Post a Comment