Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
May 19, 1998

Use reinterpret_cast<> operator for unsafe, non-portable casts

If your code contains unsafe type casts, such as casting an int to a pointer (which is not considered a standard conversion as opposed to casting an int to a float) or converting a pointer-to-function into void *, you should use the reinterpret_cast<> operator:
 
void * = (void *) 0x00ff; //C-style cast; should not be used in C++ code
 
Operator reinterpret_cast<> has the following form:
 
reinterpret_cast<to> (from)
For example:
 
void *p = reiterpret_cast<void *> (0x00fff); //correct form
You should choose the C++ cast operators over C-style cast for the following reasons:
  1. C-style cast is a deprecated feature and hence is not guaranteed to be supported in future versions of the C++ language.
  2. When using reinterpret_cast<> for unsafe casts (for example, casts of one type to another non-related type), you make your intention more explicit to both the human reader and the compiler.
  3. When porting software to different platforms, the reinterpret_cast<> statements will most likely have to be modified, so marking them in advance will make the migration task easier.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


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

 

 

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