Sign in to follow this  

extern const vs just const

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

If you intended to correct an error in the post then please contact us.

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;


}







I appreciate your help!

Share this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this