Public Group

# extern const vs just const

This topic is 5258 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi! this is a simpler example to highlight my problem with the constants declaration: My point is : i have an extern const called val which takes the value of three when it's allocated,than it's value gets changed thanks to the const_cast,than i try to change it's value ,this causes an access violation .I named it extern because i want to use it in another translation unit ,where lets say the printVal function needs it. Before when i didn't need it in another place ,it was declared as simple const which didn't give me any errors.[looksaround] I know that const_cast shouldn't be used to turn a const(which was const at the very beginning) into a non const but a nonconstant that becomes a const at runtime......

### main source file


#include "stdafx.h"
#include<iostream>
using namespace std;

extern const int val=3;
extern void printVal();

int main(int argc, char* argv[])
{

const int *pval=&val;
int * pp=const_cast<int*>(pval);

*pp=23;

cout<<&val<<"\t"<<pp<<endl;
cout<<val<<"\t"<<*pp<<endl;

printVal();

return 0;
}



### Secondary file


#include"stdafx.h"
#include<iostream>

extern const int val;

void printVal()
{

std::cout<<val;

}



##### Share on other sites
You cannot use the const_cast operator to directly override a constant variable's constant status, this causes undefined behaviour.

const_cast operator isn't mean't for this purpose it is mean't for removing the constantness of a constant pointer/reference and not constant instances they may refer to.

also another thing this line is redundant:

extern void printVal();

function prototypes are implicitly extern, which makes sense because its a declaration.

##### Share on other sites
I knew from the very begining that this is bad practice, but you must admit that you can force the compiler to accept it .This certainly is one of the few dark corners of C++ and i was just curios to see where this goes ....(most probably to a run time error) .Since in the first example it worked fine i couldn't see why this is not true in the second one too.

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 14
• 14
• 10
• 9
• 11
• ### Forum Statistics

• Total Topics
634096
• Total Posts
3015492
×