Pointers, const, constexpr and Type Aliases
程序员文章站
2024-02-29 19:32:34
...
Generally, it's best to read from right to left to understand a declearation.
const double *cptr = π
would read like:
pointer to const double
meaning we cannot use the pointer to modify underlying double variable.
int *const currErr = &errNumb;
reads:
const pointer to int
meaning the value of the pointer (i.e. the address it holds) cannot change.
some more complicated cases:
const double *const ppi = π // const pointer to const double
constexpr and type aliases brings some new problem dimemsions.
const int *p = nullptr; // pointer to const int
constexpr int *q = nullptr; // a { (const) pointer to int } as a const expression
constexpr const int *p2 = &i; // a { (const) pointer to const int } as a const expression
In a way, constexpr implies a top-level const
Type aliases also yield complicated cases:
typedef char *pstring;
const pstring cstr = 0; // const pstring i.e. const pointer to char
const pstring *ps; // pointer to const pstring i.e. pointer to const pointer to char
note replacing type aliases with the corresponding type will result in incorrect result:
const char *cstr = 0; // pointer to const char
this is different from const pstring
上一篇: Cpp:type cast
下一篇: Data Type