So I don't really understand what references do. My homework assignment is to give the output for the following code. But A,B,H always change from being and int to int&.
a) A = int, B = int, H = int
b) A = int, B = int, H = int&
c) A = int, B = int&, H = int
d) A = int&, B = int, H = int
e) A = int&, B = int, H = int&
f) A = int&, B = int&, H = int
#include<iostream>
int foo (A a, B b)
{
H h = a; a = b;
b = h; return h;
}
int main()
{
int a = 1;
int b = 2;
int r = foo (a, b);
std::cout << a << " " << b << " " << r;
return 0;
}
So, a) was obviously not a problem. But already b) confused me.
for b); int& h = a
is setting h's address to a's address? So h == Adresse of a
, meaning value of h == a
. Then a = b
(where b == 2) which makes a == b == h == 2
, so why is a == 1
in the output?
for c); h == 1
is clear, but the line a = b
I find very confusing. b is a reference, not? Does that mean, that b's address is now the same as the address of a, meaning value of a == b
? I'm guessing my thoughts are correct, because I get the proper output.
for d); h = reference of a
so a has the same address like h? Then a has the name address as b? So a == b == 2
. But now comes the weird part for me. b = h
but b == 2
, so 2 = h
, but isn't that a conflict with L/R - values? And why is h now 1?
for e); no clue, int& h ?= int& a, what happens here? h and a have the same address? Then the address of a is now b? So the address is 2? Then b holds the address of h?
for f); First, h has now the address of a, so h == a
. Then a has the same address as b. Then the address of b is the same as h. Correct thinking?
Solutions are
a) 1 2 1
b) 1 2 2
c) 1 1 1
d) 2 2 1
e) 2 2 2
f) 2 1 1
I need especially help with b) and e), thanks a lot and sorry for the long text.