c - 为什么 MISRA-C 在某些情况下不允许隐式扩大类型?

标签 c type-conversion misra

MISRA-C:2004 规则 10.1 不允许隐式扩展函数参数返回表达式 的类型,如中所示以下代码片段:

void foo1(int16_t x);

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

但是,在我的理解中,它们与分配情况没有什么不同:

s16a = s8a;                                  /* compliant     */

有什么意义?谢谢。

最佳答案

MISRA-C:2004 规则 10.1(引用的指南)指出:

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. ...

在引用的示例中,转换到更宽的整数类型(int8_t 到 int16_t),因此规则 10.1 不适用。

(10.1 和 10.2 的)扩展说明该规则的目的是防止从较宽类型到较窄类型的隐式转换。反之则没有限制!

-- 编辑添加--

作为更新,MISRA-C:2004 规则 10.1 分布在 MISRA C:2012 的多个规则中……映射表(附录 1)包括评论:

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

因此,对于 MISRA C:2012,这不再是违规行为。如果偏离 2004 年规则(恕我直言,这是正确的方法),您可能希望考虑这一点。

关于c - 为什么 MISRA-C 在某些情况下不允许隐式扩大类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52870121/

相关文章:

c++ - 为什么我不能将 uint 重新解释为 int?

c - 如何修复此代码中提到的 MISRA-2012 10.4 和 10.9 违规问题?

c - 如何使用makefile链接依赖库

c - 我怎样才能让 GetKeyState 理解大写和非大写字母

c - sprintf() 是否跨函数修改变量?

c - GTK接口(interface)结构: Why is it built as casting interface?

PHP 关联数组意外行为 - 为什么?

c++ - 生成算术运算结果类型的策略?

c - MISRA C 规则 15.5 由于多次使用具有 return 的定义而在函数中多次退出

c++ - MISRA C++ 规则 14-5-1:(不要在关联的命名空间中声明泛型函数)是否适用于 std::operator<<?