Friday, July 29, 2016

C Basics - Typedef in C

typedef allows to give a name to built-in and user defined data type.
For example,

#include <stdio.h>

typedef char BYTE;
typedef short WORD;
typedef signed char CHAR;
typedef unsigned char UCHAR;
typedef signed int INT;
typedef unsigned int UINT;

typedef struct{
 CHAR name[20];
 UCHAR city[20];
 INT zip;
}address;

int main( ) {
 
 BYTE ch;
 WORD wr;
 INT num;
 
 address home = {"Bob", "NY",10001};
 
 printf( "sizeof(BYTE):%d bytes\n", sizeof(ch));
 printf( "sizeof(WORD):%d bytes\n", sizeof(wr));
 printf( "sizeof(INT):%d bytes\n", sizeof(num));
 
 printf("Address\n");
 printf("Name: %s\n",home.name);
 printf("City: %s\n",home.city);
 printf("Zip:%d\n",home.zip);
 
 return 0;
}
The output of the above program would be:

sizeof(BYTE):1 bytes
sizeof(WORD):2 bytes
sizeof(INT):4 bytes
Address
Name: Bob
City: NY
Zip:10001

Similar to typedef, preprocessor directive #define is also used to define the aliases for various data types. But there are few difference between them.

typedef is limited to giving symbolic names to types only where as #define can be used to define alias for values(constants) as well.
typedef interpretation is performed by the compiler whereas #define statements are processed by the pre-processor.



Related topics:
Structures in C   |   Union in C   |   Enumeration in C   |   Type Casting in C   |   Type Conversion in C

List of topics: C Programming

No comments:

Post a Comment