473,721 Members | 1,827 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can I modify a constant variable through a pointer obtained from const_cast?

While I was reading about const_cast, I got curious and wanted to know
if I could modify a constant variable through a pointer which has been
"const_cast "ed. Since the pointer would be pointing to the constant
variable and if I changed the value through the pointer, the constant
variable should have been modified. Well, that's what I thought until
I wrote the following and run it.

#include <iostream>
using std::cout;
using std::endl;
int main ()
{
const int i = 0;
int &j = const_cast<int& >(i);
j = 10; // I thought this would change i, but it didn't
cout << &i << endl; // &i and &j are same as I expected
cout << &j << endl;
cout << i << endl; // but i is still 0
cout << j << endl; // and j is 10!

int * p = const_cast<int *>(&i);
*p = 30; // I change i via p
cout << &i << endl; // I confirm that p is pointing to i!
cout << p << endl; // I confirm that p is pointing to i
cout << i << endl; // i is still 0!
cout << *p << endl; // how can *p be 30 then?

return 0;
}

I am very much confused. &i and &j are same, meaning they refer to the
same location. p is also pointing to the same location. But then how
can i still be 0 and j be 10 and i still be 0 and *p 30????

Is j allocated new memory space? Is p pointing to a new location?

Can anyone kindly help me figure out what is going on?

BTW, is what I am observing is standard behaviour or particular to my
compiler (g++ version 3.2.3)?

Thank you very much in advance!
Jul 22 '05 #1
20 2088
CoolPint wrote:
While I was reading about const_cast, I got curious and wanted to know
if I could modify a constant variable through a pointer which has been
"const_cast "ed.
Let me say this right away: you can modify it, but it leads to undefined
behaviour. Once we established that, all other things are speculation,
at best.
Since the pointer would be pointing to the constant
variable and if I changed the value through the pointer, the constant
variable should have been modified. Well, that's what I thought until
I wrote the following and run it.

#include <iostream>
using std::cout;
using std::endl;
int main ()
{
const int i = 0;
Declaring a const int object does not necessarily allocate any memory
for it. Just so we're clear on that. The compiler is free to use
the actual value of the const given to it at the moment of declaration
instead of the object in memory (which, incidentally, may or may not
exist).
int &j = const_cast<int& >(i);
So far, so good.
j = 10; // I thought this would change i, but it didn't
It did. Or it didn't. Or it did, but then changed it back unbeknownst
to you. Anything can happen. No guarantees whatsoever. You broke your
own promise to the compiler: 'i' is constant. You attempted to change
it. The compiler (and the code produced by it) is not obligated to do
anything predictable or meaningful, for that matter.
cout << &i << endl; // &i and &j are same as I expected
cout << &j << endl;
cout << i << endl; // but i is still 0
Well, this is where the speculation begins. 'i' is not really 0 "still".
It has been changed. The _code_ however was created to simply use '0'
instead of 'i' for the statement above. The compiler is allowed to do
that. It optimises away memory access since you promised that the memory
is not going to be altered in any way.
cout << j << endl; // and j is 10!

int * p = const_cast<int *>(&i);
*p = 30; // I change i via p
Another cause for undefined behaviour, right here. If all bets were off
before, now they are really REALLY off.
cout << &i << endl; // I confirm that p is pointing to i!
cout << p << endl; // I confirm that p is pointing to i
cout << i << endl; // i is still 0!
cout << *p << endl; // how can *p be 30 then?

return 0;
}

I am very much confused. &i and &j are same, meaning they refer to the
same location. p is also pointing to the same location. But then how
can i still be 0 and j be 10 and i still be 0 and *p 30????

Is j allocated new memory space? Is p pointing to a new location?

Can anyone kindly help me figure out what is going on?
I hope I have. Ask more questions if you happen to have them.

BTW, is what I am observing is standard behaviour or particular to my
compiler (g++ version 3.2.3)?


Yes. And no. There is no standard behaviour. The Standard says that
the behaviour is _undefined_.
Jul 22 '05 #2
"CoolPint" <co******@yahoo .co.uk> wrote in message
While I was reading about const_cast, I got curious and wanted to know
if I could modify a constant variable through a pointer which has been
"const_cast "ed. Since the pointer would be pointing to the constant
variable and if I changed the value through the pointer, the constant
variable should have been modified. Well, that's what I thought until
I wrote the following and run it.
const_cast is only garaunteed to work when the original object was const.
If the original object is const, the compiler can substitute its values into
cout statements and so forth, so that even if you modify the variable
through a pointer the cout statement will print the original values. In
more complex examples, this replacing and evaluating of const variables at
compile time (I think it's called const folding) leads to great
optimizations. The compiler can also store the variable in read-only memory
as part of the compiled program, so that if you modify the variable through
a pointer the program will crash. In other cases, const_cast may work as
you want.
{
const int i = 0;
int &j = const_cast<int& >(i);
j = 10; // I thought this would change i, but it didn't
cout << &i << endl; // &i and &j are same as I expected
cout << &j << endl;
cout << i << endl; // but i is still 0
cout << j << endl; // and j is 10!


For cout << i, the compiler has substituted 0 into the cout statement as it
was originally const.
Jul 22 '05 #3
"Victor Bazarov" <v.********@com Acast.net> wrote in message news:O5RLc.47
#include <iostream>
using std::cout;
using std::endl;
int main ()
{
const int i = 0;


Declaring a const int object does not necessarily allocate any memory
for it. Just so we're clear on that. The compiler is free to use
the actual value of the const given to it at the moment of declaration
instead of the object in memory (which, incidentally, may or may not
exist).


True, but if you take the address of the variable and use this address, the
compiler must allocate memory for it.
int &j = const_cast<int& >(i); cout << &j << endl;

Jul 22 '05 #4
co******@yahoo. co.uk (CoolPint) wrote in
news:15******** *************** ***@posting.goo gle.com:
While I was reading about const_cast, I got curious and wanted to know
if I could modify a constant variable through a pointer which has been
"const_cast "ed. Since the pointer would be pointing to the constant
variable and if I changed the value through the pointer, the constant
variable should have been modified. Well, that's what I thought until
I wrote the following and run it.
No. It is your responsibility to ensure that the object that you
const_cast away from really isn't a const object. Any attempt to modify
a const object, through whatever means you can find, is undefined
behaviour.

Some in-line comments which will make more sense with the explanation
below:
#include <iostream>
using std::cout;
using std::endl;
int main ()
{
const int i = 0;
int &j = const_cast<int& >(i);
This refers to the variable i.
j = 10; // I thought this would change i, but it didn't
cout << &i << endl; // &i and &j are same as I expected
This has the address of the variable i.
cout << &j << endl;
cout << i << endl; // but i is still 0
Since i is declared as const, the compiler can remove the reference to i,
and rewrite this line to effectively be:

cout << 0 << endl;
cout << j << endl; // and j is 10!
This refers to the variable i.
int * p = const_cast<int *>(&i);
*p = 30; // I change i via p
cout << &i << endl; // I confirm that p is pointing to i!
cout << p << endl; // I confirm that p is pointing to i
cout << i << endl; // i is still 0!
cout << *p << endl; // how can *p be 30 then?
Same logic as above.

return 0;
}

I am very much confused. &i and &j are same, meaning they refer to the
same location. p is also pointing to the same location. But then how
can i still be 0 and j be 10 and i still be 0 and *p 30????
Since you told the compiler that i is a const int 0, anyplace that i is
used, the compiler could optimize the variable access away and replace it
with a literal 0. When you took the address of i, it needs a memory
location, so the compiler is forced to allocate memory for it. (Side
question: if you never cause the address of i to be taken, even
implicitly, is the compiler required to reserve memory space for i, or
can it completely optimize the variable out of existance?)
Is j allocated new memory space? Is p pointing to a new location?

Can anyone kindly help me figure out what is going on?

BTW, is what I am observing is standard behaviour or particular to my
compiler (g++ version 3.2.3)?


It's undefined behaviour. The compiler could format your hard drive and
cause monkeys to fly out of your nether regions (OK, from a Standard
point of view it could...).
Jul 22 '05 #5
Siemel Naran wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in message news:O5RLc.47

#include <iostream>
using std::cout;
using std::endl;
int main ()
{
const int i = 0;


Declaring a const int object does not necessarily allocate any memory
for it. Just so we're clear on that. The compiler is free to use
the actual value of the const given to it at the moment of declaration
instead of the object in memory (which, incidentally, may or may not
exist).

True, but if you take the address of the variable and use this address, the
compiler must allocate memory for it.


Yes, but only for the purpose of taking its address. The compiler is
still free to use the value in any other instances without having to
go to the [allocated due to address taken] memory object.

V
Jul 22 '05 #6
Siemel Naran posted:
const_cast is only garaunteed to work when the original object was const.


Could you please elborate on that?
-JKop
Jul 22 '05 #7

Can some-one please explain to me why "const_cast " exists
at all? From what I can see it just produces undefined
behaviour.
-JKop
Jul 22 '05 #8
JKop <NU**@NULL.NULL > wrote in news:V9******** *********@news. indigo.ie:

Can some-one please explain to me why "const_cast " exists
at all? From what I can see it just produces undefined
behaviour.


You may be attempting to call legacy code which was not const-correct.
Let's assume that you have an old C library that has a function:

void fn(data * pdata);

And it is well-documented that fn() does not modify the data.

Now, in your C++ code you have:

void cfn(const data & somedata)
{
fn(&somedata);
}
OK, you _tried_ to have that, but the C++ compiler rejects it since you
are attempting to pass a const data* where the function signature is only
data*. However, this is legal and safe:

void cfn(const data & somedata)
{
fn(const_cast<d ata *>(&somedata)) ;
}

Since fn is documented to not change the passed in data, this is safe and
legal.
I suppose a more relevent example would be:

int strcmp(char * cp1, char * cp2);

And try passing in:

std::string str1("abc"), str2("def");

std::cout << strcmp(str1.c_s tr(), str2.c_str());

(assume appropriate #include's)

Jul 22 '05 #9
On Thu, 22 Jul 2004 09:43:09 -0700, JKop wrote:
Siemel Naran posted:
const_cast is only garaunteed to work when the original object was
const.


I don't think this is correct.

Could you please elborate on that?


I suspect that Siemel Naran meant this: Taking away const by a
const_cast is guaranteed to work only if the original object was
non-const to begin with.

It is undefined behavior to modify the original object if it was
initially defined as const.

Ali
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1594
by: Anshul Sawant | last post by:
Have a look at the following code: #include<iostream> using namespace std; int main() { const int a = 1; const int* const aptr1 = &a;
4
1751
by: Markus Dehmann | last post by:
I guess this is a kind of newbie question (since most pointer questions are newbie questions). In the program below, modify(string* s) is supposed to change the content that s points to. But the main() function shows that nothing is changed at all! What am I doing wrong?
15
4116
by: Alvin | last post by:
Hello, I have been experimenting with std::vector. Say I wanted to create a vector of integers but do not want the vector to change in size or capacity. In otherwords, it has a fixed number of elements. To do this I declared a vector of 4 integers as: const vector<int> pool(4);
11
5293
by: lovecreatesbeauty | last post by:
Hello experts, Is const_cast only applied to pointers or references? If I have a constant object, then how can I remove constant attribute from it? #include <vector> #include <string> using namespace std;
12
1291
by: Bob Altman | last post by:
Hi all, I want to call a function that takes a void* argument and pass it the address of a constant. Is there a way to do this without explicitly defining the constant and then passing the address of the constant? In other words, what I *don't* want to do is this: const int myInt = 5; MyFunc(&myInt);
1
2330
by: Immortal Nephi | last post by:
How can I modify member variable inside class if member function has const like mem_Func(void) const. Please do not offer the keyword -- mutable. I want to know if keyword -- const_cast can be done. If mutable is only the solution, I will follow not to use const_cast.
5
1593
by: shuisheng | last post by:
Dear All, I have a question. Assume struct A { int *p, *q; }; struct B
8
2010
by: want.to.be.professer | last post by:
#include <iostream> using namespace std; // Check if N is constant template <int N> class ValidateConstInt{}; int main() { const int constValue = 12;
0
9365
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9127
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9056
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8002
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5973
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4483
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4748
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2569
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.