主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2023 Rule 17.7

The value returned by a function having non-void return type shall be used

自 R2024a 起

描述

规则定义

The value returned by a function having non-void return type shall be used 1 .

理由

您可能会无意中调用具有非 void 返回类型的函数,但不使用返回值。因为编译器允许此调用,所以您可能无法发现遗漏。此规则禁止调用未使用返回值的非 void 函数。如果您不打算使用函数的返回值,请将返回值显式转换为 void

Polyspace 实现

如果未使用返回值或未将其显式转换为 void 类型,检查项会标记具有非 void 返回值的函数。

检查项不会标记 memcpymemsetmemmovestrcpystrncpystrcatstrncat 函数,因为这些函数只是返回指向其第一个参量的指针。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

unsigned int cutOff(unsigned int val) {
    if (val > 10 && val < 100) {
        return val;
    }
    else {
        return 0;
    }
}

unsigned int getVal(void);

void func2(void) {
    unsigned int val = getVal(), res;
    cutOff(val);           /* Non-compliant */
    res = cutOff(val);     /* Compliant */
    (void)cutOff(val);     /* Compliant */
}

在此示例中,如果后续未使用 cutOff 的返回值,便会违反规则。

如果返回值属于以下情形之一,便不会违反规则:

  • 分配给了另一变量。

  • 显式转换为 void

检查信息

组:函数
类别:必需
AGC 类别:可读性

版本历史记录

在 R2024a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace® Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.