help me with const and type aliases


example :
1
2
3
4
5
6
7
8
9
10

typedef int *integer; // integer is a type alias for int 

int ival = 10; 
const integer p = &ival; // my book explain me in a way that i can't understand
//this definition doesn't define a pointer to const but a const pointer, why ? 

// another example : 
const integer *ps; //ps is a pointer to a constant pointer to int , why ?? 


thank you for your help..........
If you already know about pointer, I'll show you that.
typedef int *integer; is typedef int* integer;
So, you defined integer x;, will be known as int* x;

And if I understand it right(?), const integer p is a const pointer(pointing to const int's address).

And also, const integer* will be a pointer pointing to const pointer of int.
and integer* const will be a const pointer pointing to pointer of int.

well well, const integer* const will be a const pointer pointing to a const pointer of int.
Last edited on
const integer == [/code]const int *[/code] which is a pointer to a constant integer not a constant pointer to an integer. int * const is a constant pointer to an integer. Basically what you are saying is that on initialization p is equal to the address of ival so if you dereference it (*) it will have a value of 10. You change the address being pointed to by p however you may not modify the value of the address being pointed to by p. In other words
1
2
3
int other = 11;
p = other; //valid
*p = 9; //not valid 


Here is something to think about:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

int main()
{
    int const constantInteger = 11;
    int integer = 10;
    
    //int * const constantPointerToInteger = &constantInteger; //error can't point to a constant integer without having a pointer to constant integer
    int * const constantPointerToInteger = &integer; //valid can point to a constant integer
    //const int * pointerToConstantInteger = &constantInteger; //valid can point to a constant integer
    const int * pointerToConstantInteger = &integer; //valid can point to a non-const integer
    
    constantPointerToInteger = &constantInteger; //error can't point to a new address since pointer is constant
    pointerToConstantInteger = &constantInteger; //valid it can change what address it is pointing to
    
    *pointerToConstantInteger = 11; //error can't modify the value at the address the pointer is pointing to
    *constantPointerToInteger = 11; //valid it can change the value at the address the pointer is pointing to
}
Topic archived. No new replies allowed.