const用法

来源:互联网 发布:jade软件使用 编辑:程序博客网 时间:2024/05/29 16:46

很久没用const了,有点忘了。。。


const是左结合类型修饰符,它与左边的类型一起修饰右边的内容,比如int const *b,则int const限制右边的*b,但不限制b。因此,对b重新赋值不会有错误,但对*b进行重新赋值就不行(编译的时候)。

下面是一个简单的例子,基本包含了const的基本情况:

#include <stdio.h>int main(int argc, char *argv[]){        int num = 10;        const int *a = #        int const *b = #        int * const c = #        num += 1;        *a += 1;        a = NULL;        *b += 1;        b = NULL;        *c += 1;        c = NULL;        return 0;}


const.c: In function ‘main’:const.c:13:2: error: assignment of read-only location ‘*a’const.c:16:2: error: assignment of read-only location ‘*b’const.c:20:2: error: assignment of read-only variable ‘c’