Following is the syntax of typedef:
typedef old_type new_type;
Here the keyword typedef defines a new_type which is equivalent to old_type.
Let's take an example which is little more in detail-
Say we are supposed to give following new types for a 32 word length machine.
- int8 - 8 bit integer
- int16 - 16 bit integer
- int32 - 32 bit integer
- uint8 - 8 bit unsigned integer
- uint16 - 16 bit unsigned integer
- uint32 - 32 bit unsigned integer
Solution:
typedef char int8;
typedef short int int16;
typedef int int32;
typedef unsigned char uint8;
typedef unsigned short int uint16;
typedef unsigned int uint32;
Few programmers follow a convention when naming new typedefs. They use _t as suffix in their name. This helps then to know that it is user defined data type. Then above typedefs can be easily re-written as follows.
typedef char int8_t;
typedef short int int16_t;
typedef int int32_t;
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
Once this new types are available, a user can use this to declare variables of such types as follows.
uint16_t c; /* c is unsigned integer that takes 16 bytes */
Hence these new type defines will allow
- Proper control of storage needed for variable
- Define new data types which has logically correct meaning.
Links
Next Article - C Programming #32: FunctionPrevious Article - C Programming #30: Constant - enum
All Article - C Programming
No comments :
Post a Comment