Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why adding #define contsants for initializing a const is breaking rule 10.3 ?
#1
I have the folowing code :

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]
[/code]


I do not understand the reasoning why rule 10.3 is violated.
<t></t>
#2
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.
<t></t>
#3
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?
<t></t>
#4
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.
<t></t>
#5
Hi
you just have to cast your data. 2 solutions:
Code_1:
Code:
// this constrains the use of the define
#define CONST1 ((uint16_t)556U)
uint16_t const MY_var1 = CONST1;

Code_2:
Code:
#define CONST1 556U
uint16_t const MY_var1 = (uint16_t) CONST1;
<t></t>
#6
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:
Code:
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".
Posted by and on behalf of the MISRA C Working Group


Forum Jump:


Users browsing this thread: 2 Guest(s)