6

C语言const申明的使用

 3 years ago
source link: https://www.maixj.net/ict/c-const-24273
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C语言const申明的使用

2021年1月2日 / 4次阅读CC++

每个人都希望自己编写的程序能够正确的执行,没有bug(是不可能的)。C语言中的assert,可以在执行期间帮助发现定位bug,测试后编译release version,可以通过宏开关将其去掉。而const申明,可以在编译期间发生问题所在,执行期间无影响。

将一个变量申明为const,变量就变成了常量,在作用范围内,其值不允许被改变。由于C语言程序要先编译才能执行,编译器就可以发现是否有语句在对有const申明的常量进行赋值操作,哪怕是赋同样的值,编译器也会报错!哪怕是不可能被执行的语句,也会报错!

int u = 0;
const int k = 1;
if (u != 0) k = 1;

sort.c:707:19: error: assignment of read-only variable ‘k’
707 | if (u != 0) k = 1;

const申明的另一个作用,在函数接口处,表明传入的参数值不会在函数内部被改变。很多C语言标准库中的函数接口参数,都有const申明,一般他们都是 const type * 这种指针,表明安全,可放心传入,函数不会改变指针指向的内容。这也是const的一个主要的用法。定义全局常量,我们更倾向于使用#define。这也说明了,在 call by value 的传参机制上,一个 int 型的参数,申明 const 的意义不大,程序员知道自己在做什么。

const 也可以和指针变量一起使用,这样可以限制指针变量本身,也可以限制指针指向的数据。const 和指针一起使用会有几种不同的顺序,如下所示:

const int *p1; 
int const *p2;
int * const p3;
const int * const p4;
int const * const p5;

对p1和p2的申明是一样的,const int和int const是一样的,我们一般喜欢把const放在前面;

p1和p2的申明:指向p1和p2的int数据 read only,但是p1和p2本身可以修改,即可以修改指向,但是不能用来修改值;

p3的申明表示,指针本身是 read only的。

p4和p5的申明,表示指针本身,以及指向的数据都 read only,不可修改。

非const申明,可以转换成const,但是反过来不行。(函数接口的const申明,大多是这样的)

const char *p;
char *q = p;

sort.c:706:15: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
706 | char *q = p;

因为const申明转换成非const,破坏了原const语义,原来不能修改的,突然变成可以修改了。

不是所有的人都喜欢使用const,比如python中就没有const这个概念,大家都是成年人!我只是觉得有的时候,使用const可以更容易定位问题。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK