Remember one thing.
In the general case, it is impossible to convert a constant storage to a
non-constant storage.
You can cast away the const keyword, but that isn't the same as making the
const variable writeable - in some cases const variables are stored in
read-only memory - quite common for example for text strings, i.e. the
text "hello world" is often stored in the the application code (which is
write-protected). The alternative would require the compiler to copy the
text string from application code to a writeable variable on startup, i.e.
requiring the storage of the string in two different places.
Also, a lot of compilers treats const variables in a special way, i.e.
they really threat them as constants and not variables - similar to an
enum or #define.
So, if you do:
const int n = 20;
printf("%d",n);
the compiler knows that n is promised to always have the value 20. It may
then rewrite the printf() to:
printf("%d",20);
and obvisously, it doesn't matter if you manage to somehow change the
value of n - the compiler doesn't load n from any memory position but
instead uses the numeric value directly in following code.
/Per W
On Fri, 15 Apr 2005, Farzan Hajian wrote:
> Hi users,
>
> I've recently faced to some confusing results that "const_cast" makes.
> Let's assume we have the following code:
>
> const float i=55.5;
> float * j=const_cast<float*>(&i);
> cout << j << '\t' << &i << endl; // Displays addresses.
> *j=45.6;
> cout << *j <<'\t' << i << endl; // Displays contents.
>
> If you run the code you will see something like this:
> 0x22ff78 0x22ff78
> 45.6 55.5
>
> As you can see, the address of "i" is "0x22ff78" and it is the place where
> "j" points to it.
> The value of "i" is 55.5 but the value of the place where "j" points to it
> is 45.6!!
> How can a single memory block store two different values????
>
> Now there is another strange result. If you assign 45.6 to "j" immediately
> after
> "const_cast" (instead of assigning after displaying addresses) like this:
>
> const float i=55.5;
> float * j=const_cast<float*>(&i);
> *j=45.6;
> cout << j << '\t' << &i << endl; // Displays addresses.
> cout << *j <<'\t' << i << endl; // Displays contents.
>
> the result will be:
> 0x22ff78 0x22ff78
> 55.5 55.5
>
> I should mention that this distinction is made when you use DEV-C++ 5.If
> you use DEV-C++ 4,
> only the first result will be produced for both codes.
>
> I also tested the codes in MS Visual C++ 6 and it showed me the following
> result for both:
> 0012FF7C 0012FF7C
> 45.6 45.6
>
> The value of "i" is 45.6 now. I think it is more acceptable result because
> by using
> "const_cast", a constant storage (i) has been converted to a non constant
> storage (j)
> and you can change its content.
>
> Now please explain these results.
> Thanks,
|