473,396 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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 2130
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.merkerk(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);

AAAAAAAaaahhhhhhh!

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_cast<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*********@yahoo.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*********@yahoo.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'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?


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
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
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
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
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...
20
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...
12
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)...
6
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...
5
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...
11
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
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...

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.