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:
- Use only one data type for all variables used in an expression.
- 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