The difference between typedef and define

1. The typedef is intended to make alias of a variable type. The define is mainly to name a constant.

C++:
typedef unsigned int UINT;
typedef unsigned char BYTE;

#define MAX_LENGTH(100)
#define SUB(x,y) ((x)*(y))

2. The typedef is function during the compile process, which does the type verification. The define is function during the preprocess, no type verification only substitution.

3. The typedef has the effective scope while define does not.

4. When  applied to pointer, typedef and define have different result.

C++:
01 #define pCHAR char*
02 typedef char* pChar;
03 
04 int main()
05 {
06     pCHAR a,b;
07     pChar x,y;
08     char c=0,d=1;
09 
10     const pCHAR p1=&c;
11     const pChar p2=&d;
12     p1=&d;
13     *p2=2;
14     cout<<“*p1,p1”<<*p1<<p1<<endl;
15     cout<<“*p2,p2”<<*p2<<p2<<endl;
16     cout<<“size of a  is “<<sizeof a<<endl;
17     cout<<“size of b is  “<<sizeof b<<endl;
18     cout<<“size of x is “<<sizeof x<<endl;
19     cout<<“size of y is “<<sizeof y<<endl;
20     return 0;
21 }

size of a is 4

size of b is 1

size of x is 4

size of y is 4

The p1 is a constant pointer to char*, which can be modified but the content can not. It is like const char* p1.
The p2 is a pointer to constant  char*, which can not be modified but the content can. It is like char* const p2.

Advertisements
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s