Friday, 16 January 2015

struct,typedef,enum & union in C

STRUCT, TYPEDEF, ENUM & UNION
With array, we can only declare one data type per array.For different data type, we need another array declaration.It is single type aggregate data type.Struct overcomes this problem by declaring composite data types which can consist different types.

A structure is a collection of related data items stored in one place and can be referenced by more than one names.These data items are different basic data types .So, the number of bytes required to store them may also vary.


A structure type is a user-defined composite type.It is composed of fields or members which can be different types.



Struct:








typedef in C:

 The C language provides a facility called typedef for creating synonyms for previously defined data type names.   For example, the declaration:

typedef  int  Length;

makes the name Length a synonym (or alias) for the data type int. 
The data “type” name Length can now be used in declarations in exactly the same way that the data type int can be used:

Length   a, b, len ;
Length   numbers[10] ;

Typedef in structure:











Union:A union is just two or more different objects sharing the same memory.A union you use one of the elements -- every entity in a union is stored starting at the same memory address. Each entity in a struct is allocated separately. 

union { 
int a; 
char b; 
} theUnion; 

Will use sizeof(int) in memory, but if you write a char only the first 8 bits of the memory space for theUnion will be written (00 00 00 XX) or if you write an int all 32-bits will be used (XX XX XX XX) afterwards if you write a char again only the first byte will be changed (depending on

 









No comments:

Post a Comment