I'm using QAC and I get the below message for the respective source code line. How can I cast it in order for QAC to "understand" it ?
Compiler used is gcc - it doesn't warn about this issue, as it is set to "iso c99".
#define DIAGMGR_SIGNED_2_BYTES_178 ((s16)178)
sK = (s16)(sE1 / DIAGMGR_SIGNED_2_BYTES_178);
^
Result of signed division or remainder operation may be implementation defined
.
A division ('/') or remainder ('%') operation is being performed in a signed integer type and the result may be implementation-defined. Message 3103 is generated for an integer division or remainder operation in a signed type where:
- One or both operands are non-constant and of signed integer type, or
- Both operands are integer constant expressions, one of negative value and one of positive value
A signed integer division or remainder operation in which one operand is positive and the other is negative may be performed in one of two ways:
- The division will round towards zero and any non-zero remainder will be a negative value
- The division will round away from zero and any non-zero remainder will be a positive value In the ISO:C99 standard the first approach is always used. In the ISO:C90 standard either approach may be used - the result is implementation defined. For example:
/PRQA S 3120,3198,3408,3447 ++/
extern int r; extern int si; extern void foo(void) { r = -7 / 4; /* Message 3103 *//* Result is -1 in C99 but may be -2 in C90 */ r = -7 % 4; /* Message 3103 *//* Result is -3 in C99 but may be 1 in C90 */ si = si / r; /* Message 3103 */ }
You need to configure the tool so that it understands that your code is C99. In the old C90 standard, division with negative numbers could be implemented in two different ways, see this. This was a known "bug" in the C90 standard, which has been fixed since C99.
This is a standard warning for most static analysis tools, particularly if they are set to check for MISRA-C compliance. Both MISRA-C:2004 and 2012 require that the programmer is aware of this C standard "bug".
Work-arounds in C90:
If you know for certain that the operands aren't negative, simply cast them to unsigned type, or use unsigned type to begin with.
If you know that the operands might be negative:
That's unfortunately the only portable work-around in C90. Alternatively you could add a static assertion to prevent the code from compiling on systems that truncate negative numbers downwards.
If you are using C99, no work-arounds are needed, as it always truncates towards zero. You can then safely disable the warning.