MISRA Discussion Forums

Full Version: why adding #define contsants for initializing a const is breaking rule 10.3 ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the folowing code :

#define CONST1 556U
#define CONST2 420U

uint16_t const MY_var1 = CONST1;
uint16_t const MY_var2 = CONST2;
uint16_t const MY_varTotal = (CONST1 + CONST2);

And FlexeLint for C/C++ (Unix) Vers. 9.00L gives me he following message:

uint16_t const MY_varTotal = (CONST1 + CONST2);
Note 9034: Expression assigned to a narrower or different essential type [MISRA 2012 Rule 10.3, required]

I do not understand the reasoning why rule 10.3 is violated.
According to C99, a decimal constant with suffix U is of type unsigned int. (CONST1 + CONST2) is then an expression of type unsigned int. If unsigned int has a size of 32 bit in your environment, an expression with a size of 32 bit is assigned to a variable of type uint16_t which is a narrower essential type.
Thanks for the answer.
There is an exception to this rule for the direct assignment of decimal constant with suffix U, why the exception is not extended when this is the addition of such constant which results in the end in exactly the same type?
Which exception do you mean? Exception 1 states that a non-negative integer constant expression of essentially signed type may be assigned to an object of essentially unsigned type if its value can be represented in that type. But I don't see an exception about decimal constants with suffix U.
you just have to cast your data. 2 solutions:
// this constrains the use of the define
#define CONST1 ((uint16_t)556U)
uint16_t const MY_var1 = CONST1;

#define CONST1 556U
uint16_t const MY_var1 = (uint16_t) CONST1;
In the following discussion, it is assumed that uint16_t is an unsigned integer type of size 16 bits and to make the discussion easier it is assumed that "unsigned short" is also 16 bits.

Appendix D.6 shows that 556U and 420U are given the essential type of essentially unsigned short.

Appendix D.7 for + on essentially unsigned types says:
Operations subject to the  usual arithmetic conversions( * / % + - & | ^ )
2. Else if the operands are both essentially unsigned then:
   2.1 If the expression is an integer constant expression then the
       essential type of the result is the UTLR of the result;
Therefore the essential type of "556U + 420U" is that of "essentially unsigned short"since 976 fits within a 16-bit short.

There are no violations of rule 10.3 as all three assignments are from "essentially unsigned short" to "essentially unsigned short".