Detecting implicit or explicit integer conversion
Description
Checks that an integer conversion (implicit or explicit) or a write access to a bitfield does not change the value.
Why perform the check
Because C allows converting larger types to smaller integer types, some conversions can unintentionally remove significant bits of the value. The check can be limited to implicit integer conversions, which is useful when the loss of data caused by explicit conversion is considered intentional.
How to use it
Compiler option: ‑‑runtime_checking integer_conversion|implicit_integer_conversion
In the IDE: Project>Options>Runtime Checking>Integer conversion
The check can be applied to one or more modules.
The check can be avoided by inserting an explicit mask:
short f(int x)
{
return x & 0xFFFF; /* Will not report change of value */
}How it works
The compiler inserts code to perform the check at each integer conversion and at each write access to a bitfield, unless the compiler determines that the check cannot fail. Note that an explicit conversion from a constant will not be checked.
Note that increment/decrement operators (++/‑‑) and compound assignments (+=, -=, etc) are checked as if they were written longhand (var = var op val).
For example, both ++i and i += 1 are checked as if they were written i = i + 1. In this case, the addition will be checked if overflow checks are enabled, and the assignment will be checked if conversion checks are enabled. For integer types with the same size as int or larger, the conversion check cannot fail. But for smaller integer types, any failure in an expression of this kind will generally be a conversion failure. This example shows this:
signed char a = 127;
void f(void)
{
++a; /* Conversion check error (128 -> -128) */
a -= 1; /* Conversion check error (-129 -> 127) */
}The code size increases, which means that if the application has resource constraints this check should be used module per module to minimize the overhead.
Example
Follow the procedure described in Getting started using C-RUN runtime error checking, but use the Integer conversion option.
This is an example of source code that will be identified during runtime:
C-RUN will report either Integer conversion failure or Bitfield overflow. This is an example of the message information that will be listed: