Search code examples
c++referencecoutref

C++ Why do reference values change previous values?


Can somebody help me wrap my head around this? I thought the output would be 20 10 20 (in order that is ref1, num1, num2). Why does it output 20 20 20? ref1 changing also changes num1? Reference values are a new concept for me so I'm sorry if this is a stupid question. I know you guys much prefer pointer values but in class this is what we're learning about so I want to get it down. Thanks!

#include <iostream>

int main()
{
int num1 = 10;
int num2 = 20;
int &ref1 = num1;

ref1 = num2;

std::cout << "Ref1: " << ref1 << std::endl
          << "Num1: " << num1 << std::endl
          << "Num2: " << num2 << std::endl;
}

Solution

  • Why does it output 20 20 20

    ref1 is a reference to num1, so when you assign ref1 with num2 in fact you assign num1 to num2, this is the goal of the references

    so it is like if you do

    int * ref1 = &num1;
    
    *ref1 = num2;
    

    how do I find out their memory values/addresses

    ref1 on the right side (the case in the printf) gives the value of num1, to have the address of the referenced element rather than its value as usual use &, so &ref1 values &num1. Note you cannot reassign a reference, you can only initialize them