一个变量声明中的多个const

时间:2012-02-02 09:01:01

标签: c const ansi

我的一位同事在ANSI C中使用const有点疯狂,我想知道你们对它的想法。他写这样的东西例如:

const uint8* const pt_data

我明白他要去哪里,但对我来说,这使得所有这些const的阅读和可维护性变得更加困难。

4 个答案:

答案 0 :(得分:9)

这是指向const数据的const指针。

  • 第一个const会阻止*pt_data = 10;
  • 第二个const会阻止pt_data = stuff;

看起来它可能非常合法。

答案 1 :(得分:6)

const总是引用右边的单词,除非它位于行的末尾,它指的是项目本身(在更高级别的语言中)

const char* str; //This is a pointer to read-only char data
                 //Read as to (const char)* str;
                 //Thus :
                 //   *str = 'a';
                 //Is forbidden

char* const str; //This is a read-only pointer to a char data
                 //Read as char* (const str);
                 //Thus :
                 //   str = &a;
                 //Is forbidden

const char* const str; //This is a read-only pointer to read-only char data
                       //Read as (const char)* (const str);
                       //Thus :
                       //    str = &a
                       //  and
                       //    *str = 'a';
                       //Is forbidden

在声明指针时应始终初始化这些指针(除非它们是参数)

const关键字非常适合确保某些内容不会被修改,并且还告诉开发者它不应该。例如int strlen(const char* str)告诉您字符串中的char数据不会被修改。

答案 2 :(得分:5)

它是指向常量数据的常量指针 这意味着您无法更改数据(其地址为pt_data存储),也无法更改指针(pt_data)以指向其他内容(某些其他地址)。

他可能就是这样。

答案 3 :(得分:2)

如果从变量名称开始,逆时针方向移动,pt_data是指向const uint8的{​​{1}}指针。

请参阅以下原始ASCII图像:

  ,--------------------------------.
  |                                |
  |     ,------------------------. |
  |     |                        | |
  |     |   ,------------------. | |
  |     |   |                  | | |
  |     |   |    ,-----------. | | |
  |     |   |    |           | | | |
const uint8 * const pt_data; | | | |
        |   |    |     |     | | | |
        |   |    |     `-----' | | |
        |   |    |             | | |
        |   |    `-------------' | |
        |   |                    | |
        |   `--------------------' |
        |                          |
        `--------------------------'

自从我多年前在旧C书中看到这个方案以来,它帮助我理解复杂的声明。