SalvGi
SalvGi

Reputation: 59

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;
}

Upvotes: 0

Views: 185

Answers (2)

bruno
bruno

Reputation: 32586

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

Upvotes: 1

Nidhi Agrawal
Nidhi Agrawal

Reputation: 13

you can understand it as reference variable is alias, i.e just another name for existing variable thus ref1 another name of num1 when you do ref1=num2 , ref1 is assigned with num2 value i.e 20 and similary num1 get assign with 20 value

Upvotes: 2

Related Questions