Why can I change a const's value

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;
	const int &y = x;
	cout << "x: " << x << endl;
	cout << "y: " << y << endl;
	x = 4;
	cout << "x: " << x << endl;
	cout << "y: " << y << endl;
}

x: 3
y: 3
x: 4
y: 4
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.

So no, it's not a bug. That's how it's designed.
Last edited on
Hi Nikko YL,

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>

using namespace std;

int main()
{
	int x = 3;
	const int &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.

Last edited on
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
	const int &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.
Last edited on
Thanks all! :)
So I had wrong concept about const objects.


But I can't get krugle's point.
What does the address of both x and y
0x22ff48
means and what has it interpreted?
&y is defined as a constant alias for x. 0x22ff48 is just a physical address,. forget about that
Topic archived. No new replies allowed.