C Programming language

adplus-dvertising
DECLARING STRUCTURE
Previous Home Next
DECLARING STRUCTURE

 

In our example program, the following statement declares the structure type:

struct book

char  name ;
float  price ;
int  pages ;
} ;


 

This statement defines a new data type called  struct book. Each variable of this data type will consist of a character variable called name, a float variable called price and an integer variable called pages. The general form of a structure declaration statement is given below: 


struct <structure name>
{
structure element 1 ;
structure element 2 ;    
structure element 3 ;
......
......

Once the new structure data type has been defined one or more variables can be declared to be of that type. For example the variables b1, b2, b3 can be declared to be of the type struct book, as, 

struct book  b1, b2, b3 ; we can combine the declaration of the structure type and the structure variables in one statement.

For example,

struct book
{
char  name ;
float  price ;
int  pages ;
} ;
struct book  b1, b2, b3 ;

 /*-- OR Other way -- */

struct book
{
char  name ;
float  price ;
int  pages ;
} b1, b2, b3 ;

Like primary variables and arrays, structure variables can also be initialized where they are declared. The format used is quite similar to that used to initiate arrays.

struct book
{
char  name[10] ;
float  price ;
int  pages ;
} ;
struct book  b1 = { "Basic", 130.00, 550 } ;
struct book  b2 = { "Physics", 150.80, 800 } ;


Note the following points while declaring a structure type:

  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.

     
Previous Home Next