C typedef


The C language provides the typedef keyword, which you can use to give a new name to a type. The following example defines a term BYTE for a single-byte number:

typedef unsigned char BYTE;

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

BYTE  b1, b2;

By convention, definitions are capitalized to remind users that the type name is a symbolic abbreviation, but you can also use lowercase letters, as follows:

typedef unsigned char byte;

You can also Use typedef to give a user-defined data type a new name. For example, you can use typedef on a structure to define a new data type, and then use this new data type to directly define structure variables, as follows:

#include <stdio.h>#include <string.h> typedef struct Books{   char  title[50];   char  author[50];   char  subject[100];   int   book_id;} Book; int main( ){   Book book;
 
   strcpy( book.title, "C Programming");
   strcpy( book.author, "Nuha Ali"); 
   strcpy( book.subject, "C Programming Tutorial");
   book.book_id = 6495407;
 
   printf( "Book title : %s\n", book.title);
   printf( "Book author : %s\n", book.author);
   printf( "Book subject : %s\n", book.subject);
   printf( "Book book_id : %d\n", book.book_id);   return 0;}

When the above code is compiled and executed, it will produce the following results:

Book  title : C ProgrammingBook  author : Nuha AliBook  subject : C Programming TutorialBook  book_id : 6495407

typedef vs #define

#define is a C directive used to define aliases for various data types, unlike typedef are similar, but they have the following differences:

  • #typedef is limited to defining symbolic names for types, #define can not only define symbol names for types Type definition aliases can also be defined for numerical values. For example, you can define 1 as ONE.

  • typedef is interpreted by the compiler, and the #define statement is processed by the precompiler.

The following is the simplest use of #define:

#include <stdio.h> #define TRUE  1#define FALSE 0 int main( ){
   printf( "Value of TRUE : %d\n", TRUE);
   printf( "Value of FALSE : %d\n", FALSE);   return 0;}

When the above code is compiled and executed, it will produce the following results:

Value of TRUE : 1Value of FALSE : 0