C compilers - Casting to an expression is not working

In C, when variables of different data types are used in an expression, the expression is not evaluated as expected even though proper casting was used. Why does this happen?

There are many rules applied by C compiler when it generates code for an expression. These rules vary by compiler, platform architecture (8/16/32 bits), optimization levels settings, and C standard. You have to understand how your compiler evaluates expressions in order to determine how best to cast data types in an expression.

The following are a few suggestions to workaround the problem:

  1. Use only one data type for all variables used in an expression.
  2. Declare an additional variable with the same type as the expression result variable and use this in expression. For example:
    long a, b; char c; // OLD expression a = … // expression of b, c long a, b; char c; long c_new; c_new = c;// NEW expression, all variables used (a, b, c_new) has the same type a = … // expression of b, c_new
© 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.