Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why MISRA-C disallow implicitly widening a type in some circumstances?

Implicitly widening the type of a function argument or a return expression is disallowed by MISRA-C:2004 Rule 10.1, as illustrated in the following code snippet:

void foo1(int16_t x);

int16_t foo2(void) 
{
    int8_t s8a;
    ...
    foo1(s8a);                               /* not compliant */
    ...
    return s8a;                              /* not compliant */
}

But, in my understanding, they're no different than the assigning situation:

s16a = s8a;                                  /* compliant     */

What's the point? Thanks.

like image 530
dingcurie Avatar asked Nov 18 '22 00:11

dingcurie


1 Answers

MISRA-C:2004 Rule 10.1 (the cited Guideline) states:

The value of an expression of integer type shall not be implicitly converted to a different underlying type if:

  1. it is not a conversion to a wider integer type of the same signedness, or
  2. ...

In the example cited, the conversion is to a wider integer type (int8_t to int16_t) so Rule 10.1 does not apply.

The expansion (of 10.1 and 10.2) explain that the purpose of the Rule is to prevent implicit conversions from wider to narrower types. There is no restriction the other way!

-- edit to add --

As an update, MISRA-C:2004 Rule 10.1 is spread across several Rules in MISRA C:2012... the mapping table (Addendum 1) includes the comment:

Relaxed to permit implicit widening conversions on function arguments or return values.

Therefore, for MISRA C:2012 this is no longer a violation. You may wish to consider this, if deviating the 2004 Rule (which would be, IMHO, the correct approach).

like image 200
Andrew Avatar answered Jan 19 '23 21:01

Andrew