When you do this:
int square(int& x) { return x*x;};
int s = square(40); // This gives error
To fix this you do this:
int square(const int& x) { return x*x;};
int s = square(40); // This is OK
I understand that 40 is a constant but so what if I do this:
const int& x = 40
Why would that be okay only with const
keyword? Is that the way the compiler protect that no one can change the value referred to by x
?
40 is a const so we don't even know its location in memory, but shouldn't the compiler know this address, therefore changing the value from 40 to 30 for example should be allowed since the compiler can just go to address &40
and change the value to 30?