define 和 typedef 的区别

C++ 中 define 和 typedef 的区别有:

1. define 由预处理器处理,所在编译之前define的内容就已经被替换掉了。如

$ cat define.cpp #define PI 3.14 int area(double r) { return PI * r * r;
}


$ gcc -E define.cpp 
# 1 "define.cpp" # 1 "<built-in>" # 1 "<command-line>" # 1 "/usr/include/stdc-predef.h" 1 3 4 # 1 "<command-line>" 2 # 1 "define.cpp" int area(double r) { return 3.14 * r * r; // 预处理之后 PI 就已经被替换成了3.14 }

2. define 和 typedef 在处理指针时有区别,如

#define p1_int int* typedef int* p2_int;

p1_int p1, p2; // 预处理后展开为: int *p1, p2; p1为指针,p2为int p2_int p3, p4; // p3, p4 都是指针 cout << "sizeof(p1): " << sizeof(p1) << endl;
cout << "sizeof(p2): " << sizeof(p2) << endl;
cout << "sizeof(p3): " << sizeof(p3) << endl;
cout << "sizeof(p4): " << sizeof(p4) << endl;

3.define 和 typedef 的作用域不同。如:

 1 int main() {  2 #define SIZE  1024 // 此语句出现在main函数中,但是只要在此语句之后都可以使用SIZE, 不一定是在main中  3 char buf[SIZE] = "define";  4 cout << buf << endl;  5  6 typedef int INT; // typedef 有作用域,只能在次语句之后本作用域之内使用  7 INT a = 1234;  8 cout << a << endl;  9 10  foo(); 11 return 0; 12 } 13 14 void foo(void) { 15 16 char buf[SIZE] = "typedef"; // #define SIZE 1024 在 main 函数 中,但是在 foo 中仍可以使用 17 cout << buf << endl; 18 19 // INT 没有在foo函数内定义,不能使用 20 /* 21  INT b = 4321; 22  cout << b << end; 23 */ 24 }

define 和 typedef 的区别