Beruflich Dokumente
Kultur Dokumente
UNION
&
ENUMERATIONS
STRUCTURES
• Structure is user defined data type available in C that allows to combine data items of different
kinds.
• ‘struct’ keyword is used to create a structure.
• SYNTAX −
struct [structure tag] {
member definition;
member definition;
member definition;
} [one or more structure variables];
• Example of Book structure is as shown below −
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id; } book;
ACCESSING STRUCTURE MEMBERS
• Using (.) dot operator
• POINTERS TO STRUCTURES ARE ACCESSED Using (->) indirection operator
struct {
char a; //1 byte + 3 bytes padding
int b; //4 bytes a
char c; //1 byte + 3 bytes padding b b b b
total = 12 bytes
}; c
Pad
struct{
int b;//4 bytes a
char a;//1 byte b b b b
char c;//1 byte
//2 bytes of padding total = 8 bytes c
};
UNION
• A union is a special data type available in C that allows to store different data types in the same
memory location.
• SYNTAX
union [union tag] {
member definition;
member definition;
member definition; }
[one or more union variables];
• Example union AnElt {
int i;
char c;
} elt1, elt2;
elt1.i = 4;
elt2.c = ’a’;
elt2.i = 0xDEADBEEF;
ACCESSING UNION MEMBERS
• Using (.) dot operator
STRUCTURE UNION
Compiler allocates memory for all members within Compiler allocates the memory for the largest of all
structure. members within union.
Within a structure all members gets memory allocated; While retrieving data from a union the type that is
therefore any member can be retrieved at any time. being retrieved must be the type most recently stored.
One or more members of a structure can be initialized A union may only be initialized with a value of the
at once. type of its first member
TYPEDEF
• The C programming language provides a keyword called typedef, which you can use to give a
type, a new name.
• Example :
typedef long int64_t;
typedef struct ADate {
int month;
int day;
int year;
} Date;
int64_t i = 100000000000;
Date d = {1, 21, 2016};
TYPEDEF VS MACRO
TYPEDEF MACRO
Typedef is used to create a new name to an already Macros [#define] are a direct substitution of the text
existing data type before compling the whole code
eg: #define chPointer char *
typedef unsigned int UINT32 #undef chPointer
#define chPointer int *
typedef interpretation is performed by the compiler #define statements are processed by the pre-processor
ENUMERATION (ENUM)
• An enumeration is a user defined data type in C used to assign names to integral constants
• To define an enumeration keyword ENUM is used
• SYNTAX --
enum identifier {value1, value2,.... Value n};
• Example :
enum State {Working = 1, Failed = 0};
enum State {Working = 1, Failed = 0, Freezed = 0};
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
enum day {sunday = 1, monday, tuesday = 5, wednesday, thursday = 10, friday, saturday};