simple typedef definiton

how do you define an alias for the type of a const pointer to const ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 typedef int const *integer; // alias for int const* 
 
 int ival = 10; 
 integer const p = &ival; // do you know another way to do this trough type alias?


// or 
// why in this way i don't declare a const pointer to const ?

 typedef int *const integer; //alias for int *const 
 
 int ival = 10; 
 const integer const p = &ival; // same as the first example
 // the const on the left side is ignored, why ?
typedef doesn't work like #define. When you declare a const variable it doesn't matter if you put the const keyword before or after the type.

1
2
const type variable = value;
type const variable = value;

It doesn't matter if type is a typedef or not.

Also note this difference when declaring multiple variables in the same statement.

1
2
3
int* a, b;
typedef int* intP;
intP c, d;

a is of type int* but b is of type int (not a pointer).
Both c and d have type int*.

To make b a pointer in the example above you would have to add an extra asterisk.
 
int *a, *b;
Last edited on
> how do you define an alias for the type of a const pointer to const ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
    typedef const int* const const_pointer_to_const_int ;
    using const_pointer_to_const_int = const int* const ;

    // or
    typedef const int* pointer_to_const_int ;
    using pointer_to_const_int = const int* ;
    typedef const pointer_to_const_int const_pointer_to_const_int ;
    using const_pointer_to_const_int = const pointer_to_const_int ;

    const int v = 34 ;
    const_pointer_to_const_int p = &v ;

    std::cout << *p << '\n' ; // fine
    *p = 89 ; // *** error: p points to const
    p = nullptr ; // *** error: p is const
}

http://coliru.stacked-crooked.com/a/a282467e6f16f745
Last edited on
Topic archived. No new replies allowed.