【问题标题】:Use of `const` when declaring a parameter of a pointer type in C [duplicate]在 C 中声明指针类型的参数时使用 `const` [重复]
【发布时间】:2018-08-31 17:24:33
【问题描述】:

我知道将const 放在p 的类型之前可以保护p 指向的对象,但是呢:

void f(int * const p)

这样的声明合法吗?

另外,下面的有什么区别:

  1. void f(const int *p)
  2. void f(int * const p)
  3. void f(const int * const p)
  4. void f(int const *p)

【问题讨论】:

  • 你忘了一种情况:void f(int const *p),和void f(const int *p)一样。
  • 谢谢,我将编辑问题以包含此案例。
  • @Rrz0;为什么你认为这个问题应该再问一次?您没有在 SO 上找到类似的问题和答案吗?你认为其他问题的答案没有很好地解释这个话题吗?如果您有更好的解释,那么您不认为您可以将其作为其他类似帖子的答案发布吗?

标签: c pointers


【解决方案1】:

这样的声明合法吗?

是的,尽管效果与 const 位于 p 的类型之前的效果不同。

另外,下面的有什么区别:

  1. void f(const int *p)

    const放在之前 p的类型保护p指向的对象。

    例子:

    void f(const int *p) {
       int j;
    
       *p = 0;       //WRONG
       p = &j;       //legal
    }
    
  2. void f(int * const p)

    const 放在 p 的类型保护p 本身。

    例子:

    void f(int * const p) {
       int j;
    
       *p = 0;       //legal
       p = &j;       //WRONG
    }
    

    这个功能很晚才使用,因为p 只是另一个的副本 指针,很少有任何理由保护它。更难得的是 下一个案例。

  3. void f(const int * const p)

    这里const 保护p 和它指向的对象。

    例子:

    void f(const int * const p) {
       int j;
    
       *p = 0;       //WRONG
       p = &j;       //WRONG
    }
    
  4. void f(int const *p)

    这与void f(const int *p) 相同。 见第 1 点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2019-09-17
    • 1970-01-01
    相关资源
    最近更新 更多