-1

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • Is there a reason for the initialization of the two variables to be different? Once with {} and once with =. – NoDataDumpNoContribution Jul 10 '23 at 05:34
  • 1
    What error does it give? What tutorial is saying "pointers can be redefined"? I'm pretty sure it's saying "pointers can be reassigned". – 273K Jul 10 '23 at 05:37
  • @NoDataDumpNoContribution I am actually quite a beginner and there was no reason for it to be the case – Abhijit Saha Jul 10 '23 at 05:39
  • @273K what is the difference between the two? – Abhijit Saha Jul 10 '23 at 05:40
  • 4
    You seem to need to go to the beginning of the tutorial where "definition" and "assignment" are explained. – 273K Jul 10 '23 at 05:43
  • Note that you don't need to return 0 from `main()`, that can happen implicitly. – einpoklum Jul 10 '23 at 10:57
  • *"it is mentioned that pointers can be redefined"* -- paraphrasing what you read allows you to color the intent with your own misunderstanding. Or maybe the tutorial is being too loose with the terminology. Could you give an exact quote? – JaMiT Jul 12 '23 at 01:38

1 Answers1

2

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 =.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    If anyone is wondering, the variable we will be allowed to redefine in C++26 is the placeholder variable `_`. – Weijun Zhou Jul 17 '23 at 08:37