Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C typedef

C typedef

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



typedef unsigned char BYTE;

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



BYTE  b1, b2;

By convention, uppercase letters are used in definitions 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 new name to a user-defined data type. For example, you can use typedef with a structure to define a new data type name, and then use this new data type to directly define structure 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

,

"

Runoob

"

)

;

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 code above is compiled and executed, it produces the following result:



书标题 : C 教程

书作者 : Runoob

书类目 : 编程语言

书 ID : 12345

typedef vs #define

#define is a C directive used to define aliases for various data types, similar to typedef , but they differ in the following ways:

Here is the simplest use 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 code above is compiled and executed, it produces the following result:



TRUE 的值: 1

FALSE 的值: 0