UMBC CMSC 202
UMBC CMSC 202 CSEE | 202 | current 202

Type Casting in C++

In many mathematical expressions, it is often necessary to "cast" one data type (say int) to another (say double) to get the appropriate result. For example, this function (incorrectly) attempts to convert temperatures in degrees Celcius into Fahrenheit. double DegreesCelsius( int degreesFahrenheit ) { return 5 / 9 * ( degreesFahrenheit - 32 ); } This function fails to give the correct answer. The expression 5 / 9 represents integer division and therefore the decimal portion of the result is discarded. In C, we can "cast" one of the operands to be a floating-point (double) value to get the right result (yes, there is another way too) double DegreesCelsius( int degreesFahernheit ) { return (double)5 / 9 * ( degreesFahrenheit - 32 ); } In C++, this type of casting is possible, but the syntax is different. The equivalent code in C++ is double DegreesCelsius( int degreesFahernheit ) { return static_cast<double>( 5 ) / 9 * ( degreesFahrenheit - 32 ); } C++ provides other types of casts, but these are beyond the scope of this introduction.


Last Modified: Monday, 28-Aug-2006 10:15:54 EDT