關於C語言的常量

顺心无忧發表於2024-04-29
#include <stdio.h>

int main() {

    // (1)指向整型常量的指標。【const pointer】  地址:可變,值:不可變
    const int *p1; // 等價於 int const *p2;
    printf("[[constant pointer]] before change address: %p\n", p1);
    int a = 1;
    p1 = &a;
    printf("[[constant pointer]] after change address: %p\n\n", p1);

    // (2)指向整型常量的指標。【pointer to const】  地址:不可變,值:可變
    int b = 120;
    int *const p3 = &b;
    printf("[[pointer to const]] before change value: %d\n", *p3);
    *p3 = 123;
    printf("[[pointer to const]] after change value: %d\n\n", *p3);

    // (3)指向整型常量的常量指標。【const pointer to a const】  地址:不可變,值:不可變
    const int *const p4; // 等價於 int const *const p5;
    printf("[[constant pointer to a constant]]: NEITHER CAN CHANGE [addr] NOR [value]");
    return 0;
}
[[constant pointer]] before change address: 0000000000000000
[[constant pointer]] after change address: 00000025175ff98c

[[pointer to const]] before change value: 120
[[pointer to const]] after change value: 123

[[constant pointer to a constant]]: NEITHER CAN CHANGE [addr] NOR [value]
Process finished with exit code 0

相關文章