473,714 Members | 2,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const_cast undefined results

In the following code at the end of the program z = 20 & y = 99.

void doit(const int* x)
{
int* nonconst;
nonconst = const_cast<int* >(x);
*nonconst = 99;
}

int main(int argc, char* argv[])
{
const int y = 20;
int z;
doit(&y);
z = y; // Fails
return 0;
}

having looked at the generated assembler code I can see why this is
'failing' as the assembler uses a numeric literal to assign 20 to z on the
failing statement. This is logical & efficient in most cases as y is a
const which can be evaluated at compile time. However, since the facility
has been provided to un-const a const variable (bad programming practice?) I
would have thought that this code should work. I've tried it on Microsoft &
g++ compilers with the same result. I have seen a web site that said that
the result of const_cast in cases like this was undefined. I find the idea
of undefined results in programming utterly abhorrent. We might as well
accept 'nearly working' programs with such constructs as 'do sometimes'
loops etc. Can this 'undefined' result be correct or is it a bug in the
language specification / compilers?

Any comments?

Simon

Jul 22 '05 #1
6 2143
Simon Bailey wrote:
In the following code at the end of the program z = 20 & y = 99.

void doit(const int* x)
{
int* nonconst;
nonconst = const_cast<int* >(x);
*nonconst = 99;
}

int main(int argc, char* argv[])
{
const int y = 20;
int z;
doit(&y);
z = y; // Fails
return 0;
}

having looked at the generated assembler code I can see why this is
'failing' as the assembler uses a numeric literal to assign 20 to z on the
failing statement. This is logical & efficient in most cases as y is a
const which can be evaluated at compile time. However, since the facility
has been provided to un-const a const variable (bad programming practice?) I
would have thought that this code should work. I've tried it on Microsoft &
g++ compilers with the same result. I have seen a web site that said that
the result of const_cast in cases like this was undefined. I find the idea
of undefined results in programming utterly abhorrent. We might as well
accept 'nearly working' programs with such constructs as 'do sometimes'
loops etc. Can this 'undefined' result be correct or is it a bug in the
language specification / compilers?


It is correct as far as the C++ standard is concerned, and it is a bug
in your program. When you are casting away constness you are telling the
compiler "I know better; this is really not a const object". If you are
lying to the compiler you can be sure it will find a way to get back at
you. When using casts it is *your* responsibility to make sure that the
cast is correct, because you are effectively disabling the safeguards of
the compiler. This is why casts are best avoided. Good C++ code has very
few, if any, casts.

--
Peter van Merkerk
peter.van.merke rk(at)dse.nl
Jul 22 '05 #2
Simon Bailey posted:
In the following code at the end of the program z = 20 & y = 99.

void doit(const int* x)
{
int* nonconst;
nonconst = const_cast<int* >(x);
*nonconst = 99;
}
The above function's documentation would have to specify:

This function exhibits undefined behaviour if provided with a pointer to a
const object.

(. . . as ludacris as it may sound)

int main(int argc, char* argv[])
{
const int y = 20;
int z;
doit(&y);

AAAAAAAaaahhhhh hh!

z = y; // Fails
return 0;
}

having looked at the generated assembler code I can see why this is
'failing' as the assembler uses a numeric literal to assign 20 to z on
the failing statement.
Beautiful!

This is logical & efficient in most cases as y
is a const which can be evaluated at compile time. However, since the
facility has been provided to un-const a const variable (bad
programming practice?) I would have thought that this code should work.
Nope. It only works if the original object was non-const. Otherwise it's
undefined behaviour.

Consider if you have a "const" reference, but the reference refers to a non-
const object. Use of "const_cast " there would be grand.
I've tried it on Microsoft & g++ compilers with the same result. I
have seen a web site that said that the result of const_cast in cases
like this was undefined. I find the idea of undefined results in
programming utterly abhorrent.
int* const p = reinterpret_cas t<int* const>(876755);

*p = 5;
We might as well accept 'nearly
working' programs with such constructs as 'do sometimes' loops etc.
Please speak English.
Can this 'undefined' result be correct or is it a bug in the language
specification / compilers?


The C++ Standard explicitly defines "undefined behaviour" and specifies in
what situations it arises. The following qualifies as undefined behaviour:

int main()
{
int const blah = 5;

const_cast<int& >(blah) = 4;
}

And why? Because the original object was const.
-JKop
Jul 22 '05 #3

"Simon Bailey" <tr*********@ya hoo.co.uk> wrote in message
news:ei******** *******@newsfe1-win.ntli.net...
In the following code at the end of the program z = 20 & y = 99.

void doit(const int* x)
{
int* nonconst;
nonconst = const_cast<int* >(x);
*nonconst = 99;
}

int main(int argc, char* argv[])
{
const int y = 20;
int z;
doit(&y);
z = y; // Fails
return 0;
}

having looked at the generated assembler code I can see why this is
'failing' as the assembler uses a numeric literal to assign 20 to z on the
failing statement. This is logical & efficient in most cases as y is a
const which can be evaluated at compile time. However, since the facility
has been provided to un-const a const variable (bad programming practice?)
That is not correct. The facility has been provided to allow you to remove
const in a circumstance when you know that would not result in a const being
modified. A typical situation would be when you have to call legacy or badly
written code that does not use const when it should. Modifying a const is
undefined behaviour however you manage it. Having this rule allows greater
flexibility for compiler writers, for instance in code optimization.
I
would have thought that this code should work. I've tried it on Microsoft & g++ compilers with the same result. I have seen a web site that said that
the result of const_cast in cases like this was undefined.
Correct.
I find the idea
of undefined results in programming utterly abhorrent.
Well then you should avoid the circumstances which give rise to undefined
behaviour like the above.
We might as well
accept 'nearly working' programs with such constructs as 'do sometimes'
loops etc. Can this 'undefined' result be correct or is it a bug in the
language specification / compilers?

Any comments?


C and C++ have hundreds of circumstances that produce undefined behaviour.
If you don't like it then you should pick a different programming language.

john
Jul 22 '05 #4
JKop wrote:

This function exhibits undefined behaviour if provided with a pointer to a
const object.

(. . . as ludacris as it may sound)

It's not quite as ludicrous as it sounds. There's a difference between
a const object and an expression of some const type that refers to a
non-const object.
Jul 22 '05 #5
"Simon Bailey" <tr*********@ya hoo.co.uk> wrote in
news:ei******** *******@newsfe1-win.ntli.net:
I have seen a web site that said that the result of const_cast in cases
like this was undefined. I find the idea of undefined results in
programming utterly abhorrent. We might as well accept 'nearly
working'program s with such constructs as 'do sometimes' loops etc. Can
this 'undefined' result be correct or is it a bug in the language
specification > / compilers?


Performing a const_cast to remove the constness of a constant object and
then modifying that object is undefined behavior. Period. The C++
standard makes this clear.

So, you're likely wondering: what good is const_cast then?

Think of badly written API's.

Suppose there is a function you would like to use that takes as an
argument a non-const reference to an object. Unfortunately, all you have
is a const object and you'd rather not go through the trouble of creating
a non-const copy of it to pass as an argument. You look at the code of
this function and you see that the reference is never modified or passed
anywhere else! The original author of that function either neglected to
declare the reference parameter as const or was a beginning programmer
who did not understand the benefits of declaring parameters const
whenever possible.

It is a function you know will not change what's passed to it. Yet, you
have that constant object. In this case, using const_cast is appropriate
to have your new code work with the old.

There are plenty of functions that take non-const references or pointers
but which never change those parameters. const_cast is very useful in
these cases because it promotes const correctness but allows flexibility
when interacting with the real-world code that ignores it.
Jul 22 '05 #6
rookkey wrote:
Think of badly written API's.


Usually the problem. Either:

1. Something needs a non-const value and you KNOW it won't be modified.
2. You have a const value, but you know the object wasn't const to
begin with (more difficult, but not impossible).
Jul 22 '05 #7

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

Similar topics

2
2534
by: Kaspar Minosiants | last post by:
Hi , there is a question about work of const_cast The question is why the object is still reachable after a delete operation class A { int var; public: A():var(0){} ~A(){}
7
4304
by: R. Anbeeswaran | last post by:
Hi All, void main() { const int i = 20; int *p = const_cast<int*>(&i); *p = 40; cout <<"i="<< i <<"\t"<<"*p="<<*p<<"\n"; }
4
2803
by: S.Senthilvel | last post by:
hi, I am a little confused about the const_cast.I've thought it this way till now. //Proper cast int i = 10; const int* pci = &i; int *pi = const_cast<int*>(pci);
18
4840
by: johny smith | last post by:
Can someone please give me some good reference site/information for understanding when and why I would use 1.) const_cast Don't know why you would do this? 2.) reinterpret_cast. I have used this a little when I converted a primitive to a class, but would like to see other applications.
20
2087
by: CoolPint | last post by:
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;
12
2413
by: Markus.Elfring | last post by:
I am interested to know if the pointer value for the memory address can be changed by a compiler if the constness of the corresponding type is cast away. inline char* deconstify1(char const * X) { return (char*) X; } inline char* deconstify2(char const * X) { return const_cast<char*>(X); } const char source = "Test"; char* alias1 = deconstify1(source);
6
1932
by: Alexander Stippler | last post by:
Hello, I wonder if and in what cases casting const away by a const_cast can be dangerous. In one place the only way I can imagine to realize a pretty nice feature is casting away const. Now I wonder if this is dangerous. I have something like that: const Object & Object::dummy(const AType &a) const {
5
9196
by: Tom Smith | last post by:
I hardly dare ask this given the furore in another thread over strings and const... My problem is this. I am assured that casting away the constness of the return value of std::string::c_str() is an Error according to the Standard. But I need to pass it to a function (in an old and unpleasant C library, ugh) which takes an ordinary char*. What should I do? Is it really necessary to make a fresh copy of the string? (I'm not asking this...
11
5028
by: Squeamizh | last post by:
class my_class { public: my_class() : value(0) { } int& get_value() { return value; } const int& get_value() const { my_class& c = const_cast<my_class&>(*this); return c.get_value(); }
0
9187
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9080
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
9033
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
7960
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
6638
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
5961
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
4467
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
4730
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2113
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.