Expression assigned to a wider main type

I get the following warning from our analysis tool. Composite expression assigned to a wider essential type This is the code:

uint32_t result;
uint8_t resolution;

result = 1U << resolution;

I tried the following:

#define SHIFT_BY_ONE (uint8_t)1
result  = SHIFT_BY_ONE << resolution;

but then it gives this warning Shift left of signed quantity (int) so I think that I do not understand the problem correctly. How to fix this error?

+4
source share
4 answers

It sounds like you are using the MISRA-C: 2012 controller. The main type and compound expression are terms from MISRA-C, not from the C standard.

To understand anything from this warning at all, you need to examine the meaning of the main type (MISRA-C: 2012 8.10) and the compound expression (MISRA-C: 2012 8.10.3).

As for the reason for the warning, this rule 10.6:

.

, , , , , .

:

uint16_t a = 40000;
uint16_t b = 40000;
uint32_t result = a + b;

16- a b , 16- - ( ).

, , C, , uint32_t , . , - a + b --. , , , = , +.

-, MISRA-C , , .

, :

result = (uint32_t)1U << resolution;
+3

, 1U uint32_t. UINT32_C(...) :

result = UINT32_C(1) << resolution;
+2

1U, , 16- ( " " 32- ).

long :

result = 1UL << resolution;

( ((uint32_t)1U) << resolution, )

+1

1U (16-), uint32_t, " ". 16- unsigned 20 0x100000,

uint32_t result;
uint8_t resolution;
result = 1U << resolution; // Potential 16-bit assignment to a 32-bit type.

resolution .


?

I prefer to avoid casting whenever possible, and suggest 2 alternatives. Both effectively first create 1destination types without casting. The compiler will necessarily emit optimized code.

result = 1u;
result <<= resolution;
// or 
result = (result*0u + 1u) << resolution;
0
source

Source: https://habr.com/ru/post/1688078/


All Articles