Supposedly, a constant is read-only reference. Its value cannot be changed.
But the following program do change the value of const y.
Is this a bug in C++ language?
1 2 3 4 5 6 7 8 9 10
int main()
{
int x = 3;
constint &y = x;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
x = 4;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
}
const does not mean the variable cannot be changed... it only means you cannot change it through that particular variable.
In your code... y is const and therefore you cannot modify it. However that doesn't mean y cannot be modifed, as is what is happening when you modify the non-const x.
try altering the const y, you can't, because you declared y as a const having the same address as x and x is a normal variable so you can change its value.
try the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int main()
{
int x = 3;
constint &y = x;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
x = 4;
cout << "x: " << x << endl;
cout << "y: " << y << endl;
cout << "address of x: " << &x << endl;
cout << "address of y: " << &y << endl;
}
LOL
Hello
Who said the const's value should not be changeable?
'const' only denotes a tag that tells the compiler this memory location has a value bound to it that must not be changed.
your example bounds a const variable (a name for a location) to a non-const variable. There is nothing said about a non-const variable being unchangable.
const objects cannot be changed, but the only object in this program is the integer x, which is *not* const:
1 2
int x = 3; // this is an object, it occupies 4 bytes of writeable memory
constint &y = x; // this is NOT an object, this is a read-only accessor to x
references (and pointers) specify access paths to objects, which may impose additional restrictions (const or volatile), and those restrictions can be changed by casting or rebinding, but those restrictions do not change the nature of the object they lead to.