Arithmetic and Data Types - Casts

Chapter chap4 section 13

Sticking to the rule of thumb that says don't mix data types in expressions and relying on assignment conversions can lead to very clumsy code and it is sometimes useful if we can force conversions when we actually need to. This is easily done in the C programming language using a construct known as a cast. A cast is of the form

(data type name) expression

The expression

1 + 2 / 3

used in the program in the previous section could have been written

1 + 2 / (double) 3

The expression after the "/" operator is now

(double) 3

which is of type double. When working with constants this seems clumsy, it is certainly easier to write 3.0 but if the expression had involved integer variables then it does avoid unnecessary intermediate variables. Supposing k,l and m were all integer variables then the expression

k + l / m

would be evaluated using all integer arithmetic, to evaluate it using floating point arithmetic, a cast could be used thus

k + l / (double) m