devxlogo

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

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 (from)

For example:

 void *p = reiterpret_cast (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.
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist