The type cast operator is described in the type cast operator page and it allows the result of an expression to be explicitly converted to another type. Casts are sometimes necessary but are often over-used. This page looks at when you should use a type cast operator.
There are many situations where you must use a cast in your code to ensure that operations are performed in the type you desire. A common example of such a situation is the code:
This performs integer division of x by y and assigns the result 3 to scale. If instead, you want floating-point division and a floating-point result, then a cast can do that. The modified code:
would assign 3.5 to scale.
You might also use casts to prevent overflow, as in:
This assigns the value -1536 to result if an int was 16-bits wide (as it is with the MPLAB® XC8 Compiler) but:
would assign the value 64000.
In other situations, the choice to use a cast is to some extent personal preference. As a general rule, don’t cast expressions unless there is a good reason. Here are a few things to consider:
The C language rules ensure that types are implicitly converted when required. So for example, in:
the compiler must convert the long value held by input to a char type before the assignment takes place, so no cast is necessary here.
Most compilers, however, will issue a warning if an implicit conversion, like the one above, is to a smaller type where there could be a loss of data. In such a situation, you might cast the expression so that the warning is suppressed. Seeing a cast in that context can also reassure anyone reading the source code that the unusual conversion was intentional.
But casting comes at a price. Casts clutter expressions, making them more difficult for humans to interpret. They can also increase the work required to maintain code and can increase the probability of errors being introduced. Consider if the assignment above had been written with a type cast. For example:
If a change in the program’s design meant that the type of output had to be changed to int, the cast above should be reviewed. Are you confident that you would find and review every cast in your program every time you modify your code? And since casts suppress type-conversion warnings, there is no guidance to help you find the explicit type changes taking place.
If you find that your code needs type casts, consider if your code can be restructured to avoid the situation entirely.