Here, const
pointer hold the address of const
variable. like :
#include <iostream>
int main()
{
const int i = 5;
const int* ptr = &i;
}
It's working fine.
But, If I use using (Type alias) like:
#include <iostream>
using intptr = int*;
int main() {
const int i = 5;
const intptr ptr = &i;
}
GCC compiler gives an error. [Live demo]
Why pointer does not work with using
Type alias?
const intptr ptr
is an equivalent of int * const ptr
- const pointer to non-const int, not const int * ptr
- non-const pointer to const int.
If you find such right-to-left reading order for pointer declarations confusing you can utilize Straight declarations library which supplies alias templates to declare pointer types with left-to-right reading order:
const ptr<int> p; // const pointer to non-const int
ptr<const int> p; // non-const pointer to const int
Note that for const intptr
, const
is a top-level qualifier on intptr
. So const
is qualified on the pointer itself, then const intptr
means int* const
(i.e. const
pointer to non-const
int
), not const int*
(i.e. non-const
pointer to const
int
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With