c语言关键字const

2020-04-18  本文已影响0人  遇银
  1. 修饰变量为只读
pi@raspberrypi:~/study_c $ cat const.c 
#include <stdio.h>


int main()
{
        const int a = 10;
        a = 5;
        printf("a=%d",a);
        return 0;
}
pi@raspberrypi:~/study_c $ ls
const.c  hello.c  main.c  main.o  mem  MemTest.c
pi@raspberrypi:~/study_c $ 
pi@raspberrypi:~/study_c $ 
pi@raspberrypi:~/study_c $ 
pi@raspberrypi:~/study_c $ 
pi@raspberrypi:~/study_c $ 
pi@raspberrypi:~/study_c $ gcc const.c  -o const
const.c: In function ‘main’:
const.c:7:4: error: assignment of read-only variable ‘a’
  a = 5;
    ^
pi@raspberrypi:~/study_c $ 

2.修饰指针

int i = 0;                        // i是整型
const int c = 0;                // c是整型常量
const int* p1 = &c;             // p1是指针指向整型常量
int* const p2 = &i;             // p2是常量指针指向整型
const int* const p3 = &i;       // p3是常量指针指向整型常量
int const * const p4 = p3;      // p4是常量指针指向常量整形(和p3一样)

上一篇 下一篇

猜你喜欢

热点阅读