What are the differences and usage scenarios between typedef and #define in C language?
Core Differences:
-
Processing Stage
#define: Preprocessor stage, text replacementtypedef: Compiler stage, type alias
-
Scope
#define: Global scope, from definition point to end of filetypedef: Follows normal scoping rules
-
Type Checking
#define: No type checking, pure text replacementtypedef: Has type checking, compiler validates
-
Debugging Support
#define: Shows original code during debuggingtypedef: Shows alias type during debugging
Usage Scenario Comparison:
-
Type Aliases
c// typedef - Recommended typedef unsigned int uint32_t; uint32_t value = 100; // #define - Not recommended #define uint32_t unsigned int uint32_t value = 100; -
Function Pointers
c// typedef - Clear and readable typedef int (*CompareFunc)(const void*, const void*); CompareFunc compare = my_compare; // #define - Hard to understand #define CompareFunc int (*)(const void*, const void*) CompareFunc compare = my_compare; -
Structures
c// typedef - Concise typedef struct { int x; int y; } Point; Point p1 = {10, 20}; // #define - Not applicable -
Array Types
c// typedef - Type safe typedef int Array10[10]; Array10 arr1, arr2; // #define - May cause unexpected behavior #define Array10 int[10] Array10 arr1, arr2; // Only arr2 is an array
#define Advantage Scenarios:
-
Constant Definitions
c#define MAX_SIZE 100 #define PI 3.14159 #define VERSION "1.0.0" -
Conditional Compilation
c#ifdef DEBUG #define LOG(x) printf x #else #define LOG(x) #endif -
Macro Functions
c#define SQUARE(x) ((x) * (x)) #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
typedef Advantage Scenarios:
-
Improve Code Readability
ctypedef unsigned long long ull; typedef struct Node* NodePtr; -
Cross-platform Compatibility
c#ifdef _WIN64 typedef __int64 intptr_t; #else typedef long intptr_t; #endif -
Callback Function Types
ctypedef void (*Callback)(int result); void register_callback(Callback cb);
Common Pitfalls:
-
Macro Side Effects
c#define SQUARE(x) ((x) * (x)) int i = 2; int result = SQUARE(i++); // Undefined behavior -
Macro Parentheses Issues
c#define MUL(a, b) a * b int result = MUL(2 + 3, 4); // Result is 14, not 20 -
typedef Cannot Initialize Arrays
ctypedef int IntArray[10]; IntArray arr = {1, 2, 3}; // Error int arr[10] = {1, 2, 3}; // Correct