zl程序教程

您现在的位置是:首页 >  其它

当前栏目

快速理解 const int*, const int * const, and int const * 区别

快速 区别 理解 and int const
2023-09-11 14:14:58 时间

Memory Map

One way to remember the syntax (according to Bjarne Stroustrup) is the spiral rule-
The rule says, start from the name of the variable and move clockwise to the next pointer or type. Repeat until expression ends.

 

Spiral rule

The rule can also be seen as decoding the syntax from right to left.

 

const pointer to const int

从右往左 遇到 * 或者 type类型为 to 的分隔点

Hence,

  • int const* is pointer to const int
  • int *const is const pointer to int
  • int const* const is const pointer to const int

Using this rule, even complex declarations can be decoded like,

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