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

What is the purpose and best usage scenarios of the const keyword in C language?

2月18日 17:13

What is the purpose and best usage scenarios of the const keyword in C language?

const Keyword Purpose:

  1. Constant Variables

    c
    const int MAX_SIZE = 100; // MAX_SIZE value cannot be modified // MAX_SIZE = 200; // Compilation error
  2. Pointers and const

    c
    // Pointer to constant (content cannot be modified) const int *ptr1 = &value; // *ptr1 = 10; // Compilation error ptr1 = &other; // Legal // Constant pointer (address cannot be modified) int *const ptr2 = &value; *ptr2 = 10; // Legal // ptr2 = &other; // Compilation error // Constant pointer to constant const int *const ptr3 = &value; // *ptr3 = 10; // Compilation error // ptr3 = &other; // Compilation error
  3. Function Parameters

    c
    // Prevent function from modifying parameters void print_string(const char *str) { printf("%s\n", str); // str[0] = 'X'; // Compilation error } // Return constant pointer const char* get_version() { return "1.0.0"; }
  4. Structure Members

    c
    struct Point { const int x; const int y; }; struct Point p = {10, 20}; // p.x = 30; // Compilation error

Best Usage Scenarios:

  1. Function Parameter Protection

    c
    // Don't modify input data size_t string_length(const char *str) { size_t len = 0; while (str[len] != '\0') len++; return len; } // Don't modify array contents int array_sum(const int *arr, size_t size) { int sum = 0; for (size_t i = 0; i < size; i++) { sum += arr[i]; } return sum; }
  2. Global Constants

    c
    // Define in header file extern const int CONFIG_MAX_CONNECTIONS; extern const char* CONFIG_LOG_FILE; // Implement in source file const int CONFIG_MAX_CONNECTIONS = 100; const char* CONFIG_LOG_FILE = "app.log";
  3. Enum Replacement

    c
    // Use const instead of macro definitions const int ERROR_NONE = 0; const int ERROR_INVALID_PARAM = -1; const int ERROR_OUT_OF_MEMORY = -2;
  4. Class Constants (C++ style)

    c
    struct Config { const int timeout; const int max_retries; }; struct Config config = { .timeout = 30, .max_retries = 3 };

const vs #define Comparison:

  1. Type Safety

    c
    // const - Has type checking const int BUFFER_SIZE = 1024; // #define - No type checking #define BUFFER_SIZE 1024
  2. Debugging Support

    c
    // const - Debugger can view const int value = 100; // #define - Debugger cannot view #define value 100
  3. Scope Control

    c
    // const - Follows scope rules void function() { const int local = 10; } // #define - Globally effective #define local 10

Important Considerations:

  1. const Initialization

    c
    // Must initialize const int value; // Error const int value = 10; // Correct
  2. const and Pointers

    c
    // Distinguish const position const int *p1; // *p1 is const int const *p2; // *p2 is const (same as above) int *const p3; // p3 is const const int *const p4; // Both are const
  3. const and Arrays

    c
    // Array elements cannot be modified const int arr[] = {1, 2, 3}; // arr[0] = 10; // Compilation error
  4. const and Function Return Values

    c
    // Return const pointer to prevent modification const char* get_string() { return "Hello"; } // Caller cannot modify returned string const char* str = get_string(); // str[0] = 'X'; // Compilation error
标签:C语言