Constants


By declaring a variable as "const", indicates that you have no intention of modifying that variable. But this does not mean that others don't have.

"const" applies to whatever is on it's immediate left. If there is nothing, in which case it applies to whatever is on it's immediate right.

Constants must be intialised when declared.


"const" variables?



    
    
    
    
    
    
    

                    
0x0061ff0c
0x0061ff10 18 int minDrinkingAge;
0x0061ff14 16 int age;
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack

Output:

Can buy alcohol



    
    
    

                    
0x0061ff10
0x0061ff14 18 const int minDrinkingAge;
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack

minDrinkingAge may not change it's value as it has been declared as a "const".

Pointers and "const" together?



    
    
    
    

                    
0x0061ff08
0x0061ff0c 0x0061ff14 const int *luckyNum;
0x0061ff10
0x0061ff14 6 int evenNum;
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack

The pointer cannot change the value of the variable it is pointing to.



    
    
    
    
    
    
    
    

                    
0x0061ff04
0x0061ff08 0x0061ff14 const int *luckyNum;
0x0061ff0c
0x0061ff10 12 int evenNum2;
0x0061ff14 6 int evenNum1;
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack


Output:

*luckyNum: 10

*luckyNum: 12

"const" pointers?



    
    
    
    
    
    
    
    
    
    
    

                        
0x0061ff04
0x0061ff08 0x0061ff10 int *const dadAge;
0x0061ff0c
0x0061ff10 49 int mumAge;
0x0061ff14 20 int myAge;
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack

Output:

mumAge: 50

*dadAge: 50

mumAge: 51

*dadAge: 51



    
    
    
    
    
    

                        
0x0061ff04
0x0061ff08 5555555 int flatHomePh;
0x0061ff0c 0x0061ff14 int *const myHomePh;
0x0061ff10
0x0061ff14 1111111 int mumHomePh;
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack


The const pointer cannot change to point to something else.

References and "const" together?



    
    
    
    
    
    
    
    
    
 
                    
0x0061ff0c
0x0061ff10 "red" string primeCol;
0x0061ff14 const string &favCol
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack

Output:

primeCol: red

favCol: red

primeCol: blue

favCol: blue


The value of primeCol cannot be changed via the const reference favCol.



    
    
    

                    
0x0061ff0c
0x0061ff10 "pink" const string colour;
0x0061ff14
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack

Cannot bind a non-const reference to a const variable



    
    
    
    
    

                    
0x0061ff0c
0x0061ff10 "pink" const string colour;
0x0061ff14 const string &favCol
0x0061ff18 0x0061ff2d rtn addr
0x0061ff1c 0 rtn val
Stack