Is redefinition of a pointer prohibited in c++ despite the pointer not being const?

83 Views Asked by At

In the tutorial that I am following, it is mentioned that pointers can be redefined to contain the addresses of a different variable, as long as the pointer is not constant. But the following block of code gives an error regarding redefinition of a pointer (even though the pointer is not of constant type)

#include <iostream>

int main() {
    int int_data {33};
    int other_int_data =110;
    
    int *p_int_data= &int_data;
    //redefining the pointer
    int *p_int_data{&other_int_data};
    //error : redefinition of 'p_int_data' 
    
    return 0;
}

The same error is there when the pointer is constant. I wonder if it is a latest update and was not at the time of recording of the tutorial.

1

There are 1 best solutions below

1
Nitori Kawashiro On

A variable can't be re-defined unless when shadowing (there will be an exception to this with C++26). You can, however, assign to the previously declared and defined pointer:

#include <iostream>

int main(){
    int int_data {33};
    int other_int_data = 110;

    int *p_int_data = &int_data;  // declaration and definition
    p_int_data = &other_int_data; // assignment, not declaration or definition

    return 0;
}

Note that you can't assign with curly braces, only with =.