const_cast +static consts ?

Started by
3 comments, last by SCRUB 22 years, 3 months ago
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 ?   
LE SCRUB
Advertisement
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
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 ?
LE SCRUB
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.
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

This topic is closed to new replies.

Advertisement