PHP and C++ have a very convenient way to cast types. You don't have to memorize a long list of conversion functions. You just put the target type in parentheses in front of the value. However, this approach seems to have some problems, though I'm not really sure what they are XD

Simple type casts:

  • Convert to integer: (int)
  • Convert to single-precision: (double)
  • Convert to long integer: (long)
The others work the same way~ See the examples below for details.

C++ type cast example:

Sample code download: Box.net|4Shared|Dropbox|Google

P.S. The type-casting syntax is the same in C++ and PHP, so only C++ examples are shown here.

Another short cast: static_cast

Besides the (int) and (double) casts above, there is another casting method that seems safer and less prone to problems: static_cast<>. However, this method doesn't seem to work in PHP.

Format: static_cast<target type>(variable to be converted)

For example, to convert the data in the int variable x to float, the code is:

static_cast< int >(x);

C++ example:

Sample code download: Box.net|4Shared|Dropbox|Google