-->

Declaring Structure Variable

Declaring Structure Variable

Declaring Structure Variable

After declaring a structure format we can declare variable of that type.
A structure variable declaration is similar to the declaration of variables of any other data types.
It includes the following elements.
  1. The keyword “struct”
  2. The struct tag name.
  3. List of variable names separated by a comma.
  4. A terminating semicolon.
Example: struct employee e1, e2, e3;
Declares e1, e2, e3 as variables of type struct employee
Each one of these variables has three members as specified by the template. The complete declaration is
                struct employee
                                {
                                char ename[20];
                                int eno;
                                float salary;
                                };
                                Struct employee e1, e2, e3;
Note that the members of a structure themselves are not variables.
They do not occupy any memory until they are associated with the structure variable such as e1.
When the compiler comes across a declaration statement, it reserves memory space for the structure variables.

It is also allowed to combine both structure definition and variables declaration in one statement.

struct employee
{
char ename[20];
int eno;
float salary;
} e1, e2, e3;
struct \\ The use of tag name is optional here
{
char ename[20];
int eno;
float salary;
} e1, e2, e3;

In the previous declaration e1, e2, e3 are declared as structure variables representing three employees, but does not include a tag name, however this approach is not recommended for two reasons.
  1. Without a tag name we can’t use it for future declarations.
  2. Structure definition appears at the beginning of the program file, before any variables or functions are defined. They may also appear before the main. In such cases the definition is global and can be used by other functions as well.

Related Posts

Subscribe Our Newsletter