Skip to content

G) Pointers and address (more) and CONST

kalinosia edited this page Mar 13, 2021 · 1 revision

CHANGE VALUE

1

int value1 = 8;
int &value2 = value1;
value2 = 10;

cout<< "1: "<< value1 <<", 2: "<< value2<<endl;  // 1: 10, 2:10

2

void change_func(double &value){ //without & nothing change
value=6789;
}
int main(){
double value =123.45;
change_func(value);
}

3

void change(int *value){
    *value =*value+10;
};


int main(){
int value =123;
change(&value);
cout<<value<<endl;
}

4

int value_change(int value){ //int with return not void
return value+10; //or value+=10; return value;...
}
int main(){
int value_main = 10;
value_main=value_change(value_main);
cout<<value_main<<endl; // 20

Change point and CONST

    int value1 = 10;
    int *pointer = &value1;
    int value2 = 20;
    pointer = &value2;
    cout<<*pointer<<endl; // 20
    *pointer=12;  
    cout<<*pointer<<endl; //12
    cout<<value2<<endl; //12 !!!

CONST INT POINTER

    int value1 = 10;
    const int *pointer = &value1; //CONST int 
                                 // WE CAN CHANGE: value1=11;
                                // WE CANT: *pointer = 11;
    int value2 = 20;
    pointer = &value2;
    cout<<*pointer<<endl;
    //*pointer=12; //error with this
    cout<<value2<<endl;

CONST POINTER INT

    int value1 = 10;
    int * const pointer = &value1;
    *pointer = 11; //WE CAN
    cout<<value1<<endl;
    int value2 = 20;
    //pointer = &value2; // error with this - const pointer
    cout<<*pointer<<endl;
    //*pointer=12; //error with this
    cout<<value2<<endl;

CONST INT CONST *

    int value = 10;
    const int * const pointer = &value;
    pointer = value2; //ERROR 
    *pointer = 12; //ERROR
    value = 12; // OK

More, const int...

const int value = 10;
const int *pointer = &value; //const int value so const int
*pointer = 11; //ERROR 
value = 20; //ERROR

int value2 = 20;
pointer = &value2; //OK
*pointer = 12; // ERROR

Clone this wiki locally