7*4 2009-07-17 13:28 采纳率: 50%
浏览 998
已采纳

Const int * 、 const int * 和 int * 的区别是什么?

I always mess up how to use const int*, const int * const, and int const * correctly. Is there a set of rules defining what you can and cannot do?

I want to know all the do's and all don'ts in terms of assignments, passing to the functions, etc.

转载于:https://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const

  • 写回答

14条回答 默认 最新

  • ~Onlooker 2009-07-17 13:29
    关注

    Read it backwards (as driven by Clockwise/Spiral Rule):

    • int* - pointer to int
    • int const * - pointer to const int
    • int * const - const pointer to int
    • int const * const - const pointer to const int

    Now the first const can be on either side of the type so:

    • const int * == int const *
    • const int * const == int const * const

    If you want to go really crazy you can do things like this:

    • int ** - pointer to pointer to int
    • int ** const - a const pointer to a pointer to an int
    • int * const * - a pointer to a const pointer to an int
    • int const ** - a pointer to a pointer to a const int
    • int * const * const - a const pointer to a const pointer to an int
    • ...

    And to make sure we are clear on the meaning of const

    const int* foo;
    int *const bar; //note, you actually need to set the pointer 
                    //here because you can't change it later ;)
    

    foo is a variable pointer to a constant integer. This lets you change what you point to but not the value that you point to. Most often this is seen with C-style strings where you have a pointer to a const char. You may change which string you point to but you can't change the content of these strings. This is important when the string itself is in the data segment of a program and shouldn't be changed.

    bar is a constant or fixed pointer to a value that can be changed. This is like a reference without the extra syntactic sugar. Because of this fact, usually you would use a reference where you would use a T* const pointer unless you need to allow NULL pointers.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(13条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?