Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Feb 20, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Prefer const_cast<> to C-style cast to Remove Object "constness"

When you have to "unconst" an object, as in this case:
void print( unsigned char* c) { cout<<c<<endl; }

int main()
	const unsigned char *c = "some text";
	print(c); //compilation error, passing a const 						//arg to function which takes a non 				     //const arg. Need to "unconst" it first
Instead of removing the "constness" of c this way:
print( (unsigned char *) c); //C-style cast; not recommended
Use the built-in const_cast<> operator instead:
print( const_cast<unsigned char *> (c) ); //C++ style
What are the advantages? First, you make your code more readable, since your intention is now clearer: you
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date