美文网首页
c语言关键字const

c语言关键字const

作者: 遇银 | 来源:发表于2020-04-18 16:15 被阅读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.修饰指针

  • 把*读作“指针指向”,或直接读“指向”;
  • 把const读作“常量”;
  • 类型部分从右到左读。
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一样)

相关文章

网友评论

      本文标题:c语言关键字const

      本文链接:https://www.haomeiwen.com/subject/hznbvhtx.html