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?
You’re confusing constants and literals. They are similar, but not equivalent.
40is not a constant, it’s a literal.You can’t pass a literal by reference, since if you pass something by reference, it means it can be modified – literals cannot. Consider the following:
If you, however, pass a reference to a constant, it means that even if it’s a reference, the function is not permitted to modify its argument (since it’s a constant), so now you can safely pass in a literal – it now makes sense, since there’s no possibility for the function modifying its argument.