C Programming Tutorial
Computer Tutorial

Declaration of Structure



Declaration of Structure

The following code fragment shows how to declare a structure that defines the name and address fields. The keyword struct tells the compiler that a structure is being declared.
The general form of a structure declaration is :
struct structure_name
{
      type member-name;
      type member-name;
      type member-name;
      ..
      ..
} structure-variables;

Eeample :
struct addr
{
      char name[30];
      char street[40];
      char city[20];
      char state[3];
      unsigned long int zip;
};
The declaration is terminated by a semicolon. This is because a structure declaration is a statement. Also, the structure tag addr identifies this particular data structure and is its type specifier.
At this point, no variable has actually been created. Only the form of the data has been defined. When you declare a structure, you are defining an aggregate type, not a variable. Not until you declare a variable of that type does one actually exist. To declare a variable (that is, a physical object) of type addr.
struct addr addr_info;
This declares a variable of type addr called addr_info. Thus, addr describes the form of a structure (its type), and addr_info is an instance (an object) of the structure.
You can also declare one or more objects when you declare a structure.
struct addr
{
      char name[30];
      char street[40];
      char city[20];
      char state[3];
      unsigned long int zip;
} addr_info, binfo, cinfo;
It can defines a structure type called addr and declares variables addr_info, binfo, and cinfo of that type.

Remimber following points while declaring a structure

1. The closing brace in the structure type declaration must be followed by a semicolon.
2. It is important to understand that a structure type declaration does not tell the compiler to reserve any space in memory. All a structure declaration does is, it defines the ‘form’ of the structure.
3. Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined. In very large programs they are usually put in a separate header file, and the file is included (using the preprocessor directive #include) in whichever program we want to use this structure type.