When should I cast an expression?

Expressions can be explicitly cast using the cast operator, a type bound in parentheses/round brackets, e.g. (int). In all cases, the conversion of one type to another must be done with caution and only when necessary.

Consider the example:

Here, a long type is being assigned to a int type (the assignment will truncate the value in long variable l). The compiler will automatically perform a type conversion from the type of the expression on the right of the assignment operator, to the type of the lvalue on the left of the operator. This is called an "implicit type conversion".

You should not use a cast in this expression. The compiler knows the types of both operands and will perform the intended operation. If you do use a cast, there is the potential for mistakes if the code is changed. For example, if you had:

The code will work in the same way, but, if in the future the type of i is changed to a long, for example, then the programmer must remember to adjust the cast, or remove it, otherwise the contents of l will continue to be truncated by the assignment.

Only use a cast in situations where the types the compiler will use are not the types that you would like it to use. For example, consider the result of a division assigned to a floating-point variable:

In this case, integer division is performed and the result is then converted to a float format. So if i contained seven and j contained two, the division will yield three and this will be implicitly converted to a float type (3.0) and then assigned to fl. If you wanted the division to be performed in a float format, then a cast is necessary:

For example, either i or j can be cast before the division. The result assigned to fl now be 3.5.

An explicit cast may suppress warnings that might otherwise have been produced. Checking the warnings in your code is a good way to find potential bugs.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.