To Cast, or Not to Cast

Last modified by Microchip on 2024/01/16 20:06

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:

1
2
3
4
float scale;
int x = 7, y = 2;

scale = x / y;

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:

1
scale= (float) x / y;

would assign 3.5 to scale.

You might also use casts to prevent overflow, as in:

1
2
3
4
int i = 32000, j = 32000;
long int result;

result = i + j;

This assigns the value -1536 to result if an int was 16-bits wide (as it is with the MPLAB® XC8 Compiler) but:

1
result = (long int) i + j;

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:

1
2
3
4
long int input;
signed char output;

output = input;

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:

1
output = (signed char)input;

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.

Back to Top