const 修飾指針的問題

const 修飾指針的問題

判斷法則

沿着*號劃一條線:

  • 如果const位於*的左側,則const就是用來修飾指針所指向的變量,即指針指向爲常量
  • 如果const位於*的右側,const就是修飾指針本身,即指針本身是常量

驗證

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 1;
    int b = 2;

    /*const int XX 與 int const XX 等價*/
    const int* p1 = &a;
    printf("%d",*p1);
    //*p1 += 1; ERROR const此時修飾指向的內容,無法修改常量
    p1 = &b;// OK const 此時不修改指針,故指針本身值可變
    int const *p2 = &b;
    //*p2 += 1; ERROR 無法修改常量
    p2 = &a; //OK const 此時不修改指針,故指針本身值可變

    /*const 修飾指針本身*/
    int* const p3 = &a;
    *p3 += 1; // OK p3本身是常量不可變,但是可以修改所執行的內容
    //p3 = &b; ERROR 無法修改p3本身,因爲p3本身是常量

    const int* const p4 = &b;
    //*p4 += 1; ERROR 指向的內容被修飾爲常量
    //p4 = &a; ERROR 指針本身值也被修飾爲常量

    //const (int*) p = &a; syntax error
    //(int*) const p = &b; syntax error

    return EXIT_SUCCESS;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章