MISRA Discussion Forums

Full Version: Underlying type of unary minus operator (-var)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a question about underlying type of expressions involving unary minus operator. This is connected to 10.1 rule that disallows signed/unsigned conversions.

For example:
Code:
uint8_t  mc2_1209_u8a;
mc2_1209_u8a = -mc2_1209_u8a;

What is the underlying type of "-mc2_1209_u8a" expression? If it is unsigned then rule 10.1 is not violated; if it is signed then the rule is violated. (Of course this code is a violation of rule 12.9 anyway).

In my opinion the underlying type is still uint8 because C standard says in 6.5.3.3[3] (C99 cited):
Quote:The result of the unary - operator is the negative of its (promoted) operand.
The integer promotions are performed on the operand, and the result has the
promoted type.

This seems consistent with rule 12.9 which disallows using unary minus operator on unsigned operands.

Please correct me if I am wrong or if this was not the intention of MISRA rules.
The underlying type is uint8_t, which will be converted by the integer promotions to the type int. You can never assume that int is either signed or unsigned. As I see it, you must therefore always typecast to conform with MISRA:

mc2_1209_u8a = (uint8_t) -mc2_1209_u8a;

However, I believe that the following should also be compliant:

mc2_1209_u8a -= mc2_1209_u8a;
The result of applying a unary minus to an operand of unsigned int is unsigned int according to the C standard.

Similarly, for the purpose of completing the concept of underlying type, the following applies:

Quote:The underlying type which results from the unary minus operator is the underlying type of the operand.

However, Rule 12.9 applies and an expression of this type should be viewed with suspicion.
[ID:0000008]