C++ Casts to be avoided
y = i/double(7); //would do division
// in double
ptr = (char*)(i + 88); //int to pointer value
These older forms are considered obsolete. Many older compilers and older source code use them, but they should be replaced by the
use of static_cast
whenever possible.
Using cast for type conversion
Occasionally, you need to store a value into a variable of a different type.
Whenever there is the risk of information loss, the compiler issues a warning.
For example, if you store a double value into an int variable, you can lose information in two ways:
- The fractional part is lost.
- The magnitude may be too large.
For example,
int p = 1.0E100; // NO
is not likely to work, because 10
100 is larger than the largest representable integer
Nevertheless, sometimes you do want to convert a floating-point value into an integer value.
If you are prepared to lose the fractional part and you know that this particular floating-point number is not larger than the largest possible integer, then you can turn off the warning by using a cast.
Cast: a conversion from one type (such as double) to another type (such as int) that is not safe in general, but that you know to be safe in a particular circumstance.
You express this in C++ as follows:
int n = static_cast < int >(y + 0.5);
Before the static_cast notation (see the syntax listed below) was invented, C++ programmers used a different notation, shown below:
int n = (int)(y + 0.5);
Syntax of Cast
static_cast<type_name>(expression)
Example:
static_cast<int>(x + 0.5)
Purpose: Change an expression to a different type.