MISRA C:2004, error with bit shifting

后端 未结 3 835
甜味超标
甜味超标 2021-01-06 03:59

I\'m using IAR Workbench compiler with MISRA C:2004 checking on.
The fragment is:

#define UNS_32 unsigned int
UNS_32 arg = 3U;
UNS_32 converted_arg = (         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-06 04:06

    In C89, which the MISRA rules specify, the type of an integer constant suffixed with a U is the first of the list "unsigned int, unsigned long int" in which its value can be represented. This means that the type of 1U must be unsigned int.

    The definition of the bitwise shift operator specifies that the integer promotions are performed on each operand (this does not change an unsigned int), and that the type of the result is the type of the promoted left operand. In this case, the type of the result of (1U << converted_arg) is therefore unsigned int.

    The only explicit conversion here is the cast of this unsigned int value to unsigned int, so this must be what the compiler is warning about - although there is no unsigned char in sight, which means that the checker appears to be buggy.

    Technically though, this cast from unsigned int to unsigned int does appear to violate rule 10.3, which says that the result of "complex expression" can only be cast to a narrower type - and casting to the same type is clearly not casting to a narrower type.

    The cast is unnecessary - I would simply omit it.

提交回复
热议问题