首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C 語言 const 與指針完全指南:四種組合、多級指針、函數參數最佳實踐

     編輯:C++ 入門

四種基本組合

核心規則:從右向左讀

const int *p;        // p 是指針 -> 指向 int 常量
int *const p;        // p 是常量指針 -> 指向 int
const int *const p;  // p 是常量指針 -> 指向 int 常量

指向常量的指針(最常用)

int num = 5;
const int limit = 500;
const int *pci = &limit; // OK
pci = #              // OK:指針可改
// *pci = 10;            // ERROR:不能通過 pci 修改值

// 函數參數保護:防止函數內部修改參數指向的數據
void printArray(const int *arr, int n) {
    // arr[i] = 0; // 編譯錯誤
    for (int i=0; i

常量指針

int num = 10;
int *const cpi = # // 必須初始化
*cpi = 20;             // OK:修改指向的值
// cpi = &other;       // ERROR:指針不可改

多級指針與 const 傳播

struct Node { int x; };
const Node* createNode() {
    Node* p = (Node*)malloc(sizeof(Node));
    p->x = 0;
    return p; // 返回指向常量的指針
}

void useNode(const Node* p) {
    int val = p->x;     // OK 讀取
    // p->x = 1;        // ERROR 寫入
}

int main() {
    const Node* p = createNode();
    useNode(p);
    // 釋放需轉型(謹慎!僅當確知原對象非常量)
    free((Node*)p); 
}

常見錯誤與避坑

  • 字符串字面量:char *s = "hello" 危險!應 const char *s = "hello"(字面量在只讀段)
  • const 轉非 const:const_cast (C++) 或強制轉型 (C) 破壞常量性,導致未定義行為
  • 數組參數:void f(int a[]) 等價 void f(int *a),加 const 保護:void f(const int a[])

總結:const 使用原則

  1. 盡可能使用:讓編譯器幫你發現邏輯錯誤
  2. 函數參數優先:輸入指針必加 const
  3. 右向左讀:搞清修飾的是指針還是指向值
  4. 不要cast away const:除非極少數底層交互必要
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
聲明指針可改指向值可改含義
int *p是是普通指針
const int *p / int const *p是否指向常量的指針
int *const p否是常量指針(指針本身不可改)
const int *const p否否指向常量的常量指針