msc
msc

Reputation: 34628

using type alias doesn't work with "const" pointer

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?

Upvotes: 6

Views: 897

Answers (3)

user7860670
user7860670

Reputation: 37600

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

Upvotes: 5

nyronium
nyronium

Reputation: 1278

The const keyword is actually binding to the word to the left of it. The notable exception is when the only word it can bind to is on the right hand side.

This means const int* ptr can be rewritten as int const* ptr while const intptr ptr is equivalent to intptr const ptr which is int *const ptr.

Upvotes: 0

songyuanyao
songyuanyao

Reputation: 172964

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).

Upvotes: 3

Related Questions