就近原则—const关键字的使用

在C中,const关键字的用途就是使函数操作时不改变其修饰的变量的值。平常我们见得多的const用法有如下几种,似乎可以总结为“就近原则”:即const最靠近其右边哪个变量,就说明那个变量为常量。”

C语言中const用法
 
 

在Linux0.11中读到skip_atoi()函数代码,如下:

static int skip_atoi(const char **s)
{
    int i = 0;

    while (is_digit(**s))
         i = i * 10 + *((*s)++) - '0';

    return i;
}

函数功能很清楚,就是完成数字字符串(alpha) 到整数(int)的转化。但传递给skip_atoi()的参数类型却让我有些迷惑,对指向指针的指针(**)倒不存在什么理解上问题,关键在于参数中 const到底是修饰s, *s, 还是**s呢?

    在C中,const关键字的用途就是使函数操作时不改变其修饰的变量的值。平常我们见得多的const用法有如下几种,似乎可以总结为“就近原则”:即const最靠近其右边哪个变量,就说明那个变量为常量。”

const int *p1; /* p1所指向的int变量值不可改变,为常量,但可以改变p1指针的值 */
int * const p2; /* p2指针为常量,即p2的值不可改变,但可以改变p2指向对象的值 */
const int * const p3; /* p3指针是常量,同时p3所指向int对象的值也是常量 */

俗话说,凡事都讲究个有理可据,此处也不例外。从K & R 《The C Programming Language》(2nd)总算找到相关说明:

A.8.6.1 Pointer Declarators

In a declaration T D where D has the form

* type-qualifier-listopt D1

and the type of the identifier in the declaration T D1 is ``type-modifier T,'' the type of the identifier of D is ``type-modifier type-qualifier-list pointer to T.'' Qualifiers following * apply to pointer itself, rather than to the object to which the pointer points.

由上可知,对于声明,我们均以*号界定,并加以解析:

如const char **s;

解析理解为:

以最右边第一个*号开始界定,形式为const char ** | s, 由于s前没有修饰符,因此可以改变指针值;s是指向const char *类型对象的指针,事实上const char *就是指针,因此s也就是指向指针的指针;

再以第二个*号来界定,形式为const char * | *s,由于*s前没有修饰符,因此其值是可以改变的;

最后再来解析const char *对象,类似于前面谈到的const int *p1,因此表示该指针(*s)所指向的对(此处为字符串)为常量,其值不可改变;


同样,如果有声明如下:

const char ** const s;

解析它也只是s指针前多了修饰符const,因此s指针本身是常量,指针值不可改变;其余意义同上面(2)(3)所述。

最后,给出相关测试代码:

int main()
{
    int a1 = 1;
    int a2 = 2;    
    const int *p1 = &a1;
    int * const p2 = &a2;
    const char *fmt = "hello";
    const char **s = &fmt;

     p1 = &a2;    
    *p1 = a2;    // error

    p2 = &a1;    // error
    *p2 = a1;  
    (*s)++;
     s++;
    (**s)++;    
// error

    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值