Jun 29, 2014

C Programming #31: - Typedef part1

Typedefs are used to create new data types. Till now we have seen data types such as character, integer, float etc, these are called as basic data types. C allows you to create your own data type called as typedefs (Short for type definition). As the name indicates this article is short introduction to typedefs. Part 2 will cover rest of the concepts later.



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.
  1. int8  - 8 bit integer
  2. int16 - 16 bit integer
  3. int32 - 32 bit integer
  4. uint8 - 8 bit unsigned integer
  5. uint16 - 16 bit unsigned integer
  6. 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
  1. Proper control of storage needed for variable
  2. Define new data types which has logically correct meaning.
Once structure, union, bitfields and functions are introduced typedefs will be re-visited with part 2.

Links

Next Article - C Programming #32: Function
Previous Article - C Programming #30: Constant - enum
All Article - C Programming

No comments :

Post a Comment