C typedef

The C language providestypedefkeyword, you can use it to give a new name to a type. The following example defines a term for a single-byte numberBYTE:

typedef unsigned char BYTE;

After this type definition, the identifier BYTE can be used as a type.unsigned charabbreviations, such as:

BYTE  b1, b2;

By convention, the definition uses capital letters 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 usetypedefto give a new name to a user-defined data type. For example, you can use typedef on a struct to define a new data type name, and then use this new data type to directly define struct variables, as follows:

Example

#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 Tutorial"); strcpy( book.author, "Example"); strcpy( book.subject, "Programming language"); book.book_id = 12345; printf( "Book Title : %s\n", book.title); printf( "Book Author : %s\n", book.author); printf( "Book Category : %s\n", book.subject); printf( "Book ID : %d\n", book.book_id); return 0; }

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

书标题 : C 教程
书作者 : Example
书类目 : 编程语言
书 ID : 12345

typedef vs #define

#defineis a C directive used to define aliases for various data types, andtypedefsimilar, but they have the following differences:

  • typedefLimited to defining symbolic names for types,#defineIt can not only define aliases for types, but also define aliases for values; for example, you can define 1 as ONE.
  • typedefis interpreted by the compiler,#defineThe statement is processed by the preprocessor.

The following is the simplest usage of #define:

Example

#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 produces the following results:

TRUE 的值: 1
FALSE 的值: 0
other extensions