The reason why is implicit type promotions. There is 3 implicit promotions in that single line, which is dangerous and sloppy style. You have both integer promotion/usual arithmetic conversions and an implicit lvalue conversion in a single line of code.
You must understand how these coversions work in C, in order to write bug free C code, but you must also understand them in order to use MISRA-C. In fact, one of the purposes of MISRA-C has always been to educate programmers about implicit type promotions - you'll also find explanations in the MISRA-C document.
Your code actually violates several MISRA-C:2012 rules. Not only 10.3 which is concerned about the implicit lvalue conversions, but also 10.4:
Both operands of an operator in which the usual arithmetic conversions are performed shall have the same essential type category.
var4
is essentially signed and var5
is essentially unsigned. Therefore it is not enough to just cast the result to the appropriate type. To get MISRA-C compliant code you must cast both operands to the same type. Or better, use variables of appropriate type to begin with: it does not make much sense to store the result of -10 + 15
in an unsigned variable. Either you need signed numbers or you don't.
To get MISRA-C compliant code which is also fully portable, this should be a type that cannot get implicitly promoted, like uint32_t
.
uint8_t var6 = (uint8_t) ((uint32_t)var4 + (uint32_t)var5);
alternatively
int8_t var6 = (int8_t) ((int32_t)var4 + (int32_t)var5);
This expression is rugged, professional C as it does not contain a single implicit promotion. It is self-documenting code, as it shows that the programmer knows about and has considered implicit type promotions. It does not affect performance compared to the expression with only 8 bit operands, since the compiler is free to optimize.