Keyword typedef in C

The C program language provides a typedef keyword, which you can use to provide the type for a new name. Here is an example to define a BYTE entry for 1-byte numbers (like unsigned char).

The C program language provides a typedef keyword, which you can use to provide the type for a new name. Here is an example to define a BYTE entry for 1-byte numbers (like unsigned char).

 typedef unsigned char  BYTE ; 

After defining this type, the BYTE identifier can be used as an abbreviation for unsigned char types, for example:

 BYTE b1 ,  b2 ; 

By convention, uppercase letters are used for these definitions to make it easier for users to remember, but you can use lower case letters as follows:

 typedef unsigned char byte ; 

You can also use typedef to provide a name for the user defined data type. For example, you can use typedef with a structure to define a new data type and then use that data type to define structure variables directly as follows:

 #include #include typedef struct Books { char  tieude [ 50 ]; char  tacgia [ 50 ]; char  chude [ 100 ]; int  id ; } Book ; int  main ( ) { Book  book ;  strcpy (  book . tieude , "Lap trinh C" );  strcpy (  book . tacgia , "Pham Van At" );  strcpy (  book . chude , "Ngon ngu lap trinh C" );  book . id  = 1234567 ;  printf ( "Tieu de: %sn" ,  book . tieude );  printf ( "Tac gia: %sn" ,  book . tacgia );  printf ( "Chu de: %sn" ,  book . chude );  printf ( "ID: %dn" ,  book . id );  printf ( "n===========================n" );  printf ( "QTM chuc cac ban hoc tot! n" ); return 0 ; } 

Compiling and running the above C program will result:

Picture 1 of Keyword typedef in C

typedef vs #define in C

#define is a directive in C which is also used to define aliases (abbreviations) for diverse data types similar to typedef but there are the following differences:

The typedef is limited to providing abbreviations for types only, while #define can be used to define nicknames for both values, as you can define 1 as ONE, .

The typedef translation is performed by the compiler, while the #define command is processed by the preprocessor.

Here is the simplest use of #define :

 #include #define  TRUE  1 #define  FALSE  0 int  main ( ) {  printf ( "Gia tri TRUE tuong duong: %dn" ,  TRUE );  printf ( "Gia tri FALSE tuong duong: %dn" ,  FALSE );  printf ( "n===========================n" );  printf ( "QTM chuc cac ban hoc tot! n" ); return 0 ; } 

Compiling and running the above C program will result:

Picture 2 of Keyword typedef in C

According to Tutorialspoint

Previous lesson: Bit field in C

Next lesson: Input & Output in C

« PREV POST
READ NEXT »