That’s what happened to me when I tried to do the challenge and thought “Hmm, you can’t reassign references, so I should just try to do it and see it crash.”
Here’s the output:
The code:
#include "stdafx.h"
#include <iostream>
int val = 1;
int val2 = 2;
int * valPtr = &val;
int & valRef = val;
void printVals() {
std::cout << "Values:\n";
std::cout << "val: " << val << " val2: " << val2 << " valPtr: " << *valPtr << " valRef: " << valRef << std::endl;
std::cout << "Addresses:\n";
std::cout << "val: " << &val << " val2: " << &val2 << " valPtr: " << valPtr << " valRef: " << &valRef << std::endl << std::endl;
}
void repointReference() {
// try repointing the reference, but it should crash:
valRef = val2;
std::cout << "Repointed reference! This should not work!\n";
// but it doesn't crash!!!??! Why?
}
void rewriteValueAtReference() {
std::cout << "Change value to 1234 at reference:\n";
valRef = 1234;
}
int main()
{
printVals();
repointReference();
printVals();
rewriteValueAtReference();
printVals();
return 0;
}
So, why doesn’t it crash although I reassigned the reference to val2? It even works and shows the correct value?
Think about it. The solution is below.
It took me a couple of minutes to figure it out:
The syntax I used to “reassign” the reference is actually just the syntax to to copy a value from one variable to another. You can see that in the output screenshot, too, since the value of valRef changed, but the address did not change.
Bonus question:
Is there even a syntax I could use to really try to reassign a reference?