乐闻世界logo
搜索文章和话题

What are the differences and usage scenarios between typedef and #define in C language?

2月18日 17:21

What are the differences and usage scenarios between typedef and #define in C language?

Core Differences:

  1. Processing Stage

    • #define: Preprocessor stage, text replacement
    • typedef: Compiler stage, type alias
  2. Scope

    • #define: Global scope, from definition point to end of file
    • typedef: Follows normal scoping rules
  3. Type Checking

    • #define: No type checking, pure text replacement
    • typedef: Has type checking, compiler validates
  4. Debugging Support

    • #define: Shows original code during debugging
    • typedef: Shows alias type during debugging

Usage Scenario Comparison:

  1. 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;
  2. 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;
  3. Structures

    c
    // typedef - Concise typedef struct { int x; int y; } Point; Point p1 = {10, 20}; // #define - Not applicable
  4. 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:

  1. Constant Definitions

    c
    #define MAX_SIZE 100 #define PI 3.14159 #define VERSION "1.0.0"
  2. Conditional Compilation

    c
    #ifdef DEBUG #define LOG(x) printf x #else #define LOG(x) #endif
  3. 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:

  1. Improve Code Readability

    c
    typedef unsigned long long ull; typedef struct Node* NodePtr;
  2. Cross-platform Compatibility

    c
    #ifdef _WIN64 typedef __int64 intptr_t; #else typedef long intptr_t; #endif
  3. Callback Function Types

    c
    typedef void (*Callback)(int result); void register_callback(Callback cb);

Common Pitfalls:

  1. Macro Side Effects

    c
    #define SQUARE(x) ((x) * (x)) int i = 2; int result = SQUARE(i++); // Undefined behavior
  2. Macro Parentheses Issues

    c
    #define MUL(a, b) a * b int result = MUL(2 + 3, 4); // Result is 14, not 20
  3. typedef Cannot Initialize Arrays

    c
    typedef int IntArray[10]; IntArray arr = {1, 2, 3}; // Error int arr[10] = {1, 2, 3}; // Correct
标签:C语言