【问题标题】:declaration of const pointer vs declaration of const integerconst 指针的声明与 const 整数的声明
【发布时间】:2020-08-29 08:01:55
【问题描述】:

谁能解释一下下面两段代码的区别:

func1 (...)
{
    int32_t index;
    const int32_t *p;
    p =& (index);
}
func2 (...)
{
     const int32_t s;
     s=10;  
}

可以声明一个 const 指针,然后给它赋值,但不能声明一个普通变量,然后给它赋值。谁能给我解释一下?

我收到一个 pc-lint 错误,我必须在函数内声明 const 变量,但我做不到。我怎样才能摆脱这个错误?

非常感谢。

【问题讨论】:

  • 您可以在声明中添加“number_of_stars + 1”constconst 适用于其直接右侧的任何内容:int [const] * [const] * ... [const] foo = value;
  • const int32_t s; s = 10; 编译器错误 ... int32_t * const p; p = NULL; 编译器错误

标签: c variables memory constants pc-lint


【解决方案1】:

那是因为他们没有做同样的事情(使用T作为类型,因为我基本上是懒惰的):

const T *p; // non-const pointer to const T.
const T s;  // const T.

可能将前者视为具有约束力的 [const T] [*p]

如果你想要一个const 指针,你可以使用以下之一:

T * const p;         // const pointer to non-const T, [T*] [const p]
const T * const p;   // const pointer to const T, [const T*] [const p].

【讨论】:

    【解决方案2】:
    int i=0;
    const int *p=&i;
    *p = 10; /*error*/
    

    这是incorrect,因为p被声明为pointer to constant int,所以你不能通过p改变p指向的整数值。

    int i=0;
    int const *p=&i;
    *p = 10; /* i will be 10 */
    

    这是correct,因为p被声明为constant pointer to int,所以你可以通过p改变p指向的整数值。

    int i=0;
    const int const *p;
    p = &i;  /*error*/
    *p = 10; /*error*/
    

    这是incorrect,因为p被声明为constant pointer to constant int,所以你既不能改变p指向的整数值,也不能改变p声明后的值。

    【讨论】:

      【解决方案3】:

      “可以声明一个const指针,然后给它赋值……”

      const int32_t *p 不是指向int32_tconst 指针。它是指向const int32_t 的非const 指针。

      int32_t * const p; 会给你一个const 指向int32_t 的指针。注意const 说明符位于* 声明符的右侧。

      您可以随意修改指针本身,因为它不是const,所以p = &(index); 很好。注意括号是多余的。

      "...但是不能声明一个普通的变量然后给它赋值。"

      const int32_t s; 不是“正常可修改”变量。它是用const 声明的。您不能在定义/初始化后分配 const 变量。您只能在其定义处对其进行一次初始化。

      因此,使用

       const int32_t s;
       s = 10; 
      

      当然会给你一个错误。

      我怎样才能摆脱这个错误?

      在其定义处初始化s

      const int32_t s = 10; 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-13
        • 2011-01-10
        • 2022-01-19
        • 2021-05-08
        • 2011-11-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多