Archived

This topic is now archived and is closed to further replies.

SCRUB

const_cast +static consts ?

Recommended Posts

im having problems taking the const off static variables.
  
static const screenWidth = 640;

int *x =0 ;
x = const_cast<int *> (&screenWidth);
x = 100;
[/souce]

gives me an error when trying to specify x with a value.
If it is just a const it works fine. But if its a static const
it buckles !!. It compiles and links fine but dies when using it.

any idea''s ?   

Share this post


Link to post
Share on other sites
This may be a typo, but shouldn''t that read...

*x = 100;

Otherwise you are just setting the address of pointer x to 100. I''m assuming you probably have something that tries to access the contents of what x points to (*x) later on, and that is probably where your error is popping up. That it would work at all as it is, is suprising.

D

Share this post


Link to post
Share on other sites
Indeed your right ..sorry this is it
  
int *x =0 ;
x = const_cast<int *> (&screenWidth);
*x = width;


now its definatly to do with it being static, but I really need
it to remain static ...and const.

Can anyone see a way out or even explain why it dies because
its static ?

Share this post


Link to post
Share on other sites
because static const is interpretted as the same thing as #define by many compilers. The value you''re trying to modify is probably in program memory, and protected by the OS as read-only. Casting away const is the paramount of all programming sins, so your program has justly punished you for it.

Share this post


Link to post
Share on other sites
declaring variables and functions static to hide them in the module they are in - in terms of linkage
is a deprecated feature in the C++ standard

the new way to accomplish the same thing is an anonymous namespace

in a .cpp file:

namespace
{
const int screenWidth = 640;
}


Will acomplish the same as the older ''static const''

and will likely alleviate your problem

Share this post


Link to post
Share on other sites