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

What is the difference between const int*, const int * const, and int const *?

1个答案

1

The declaration styles of these three pointer types appear similar, but they have distinct meanings and purposes. I will explain each one in detail with examples.

  1. *const int - This pointer is used to point to a constant integer. It means that the content pointed to cannot be modified through this pointer, but the pointer itself can be changed, i.e., it can point to another constant integer.

    Example:

    cpp
    int a = 10; int b = 20; const int* ptr = &a; // ptr points to a, but cannot modify a through ptr // *ptr = 11; // Error: cannot modify the content pointed to by ptr ptr = &b; // Correct: can change ptr's target
  2. *const int const - This pointer is a constant pointer to a constant integer. The first const modifies the integer pointed to (i.e., the integer is constant), and the second const modifies the pointer itself (i.e., the pointer is constant). This means that neither the content pointed to nor the pointer's target can be modified.

    Example:

    cpp
    int c = 30; int d = 40; const int* const ptr2 = &c; // ptr2 is a constant pointer to constant integer c // *ptr2 = 31; // Error: cannot modify the content pointed to by ptr2 // ptr2 = &d; // Error: cannot change ptr2's target
  3. *int const - This declaration is equivalent to const int*, indicating that the integer content pointed to is constant, i.e., it cannot be modified through the pointer, but the pointer itself can point to other addresses.

    Example:

    cpp
    int e = 50; int f = 60; int const* ptr3 = &e; // Equivalent to const int* // *ptr3 = 51; // Error: cannot modify e through ptr3 ptr3 = &f; // Correct: can change ptr3's target

In summary, understanding the combination of pointers and the const keyword is crucial for protecting data from unintended modifications, optimizing program performance, and improving code readability. Through these examples, I hope to clearly illustrate their differences and uses.

2024年7月5日 10:43 回复

你的答案