主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 17.4

All exit paths from a function with non-void return type shall have an explicit return statement with an expression

描述

规则定义

All exit paths from a function with non-void return type shall have an explicit return statement with an expression 1 .

理由

如果非 void 函数未显式返回值,但调用函数使用了返回值,则行为未定义。要防止这种行为:

  • 您必须为 return 语句提供显式表达式。

  • 您必须确保在运行时,至少执行一次 return 语句。

有一个例外,如果使用的是 C99 或更高版本,在 main() 函数中缺少显式 return 语句将视为合规。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

int absolute(int v) {
    if(v < 0) {
        return v;
    }
} // Non-compliant   


int main(){
	//...
} //Compliant by exception

在此示例中,函数 absolute 违反了此规则,因为 v >= 0 时执行路径中没有 return 语句。由于该规则不要求在 main() 函数中显式使用 return 语句,因此 Polyspace® 不会报告 main() 函数中的任何违规情况。

#define SIZE 10
int table[SIZE];

unsigned short lookup(unsigned short v) {
    if((v < 0) || (v > SIZE)) {
        return; // Non-compliant 
    }
    return table[v];
} 

在此示例中,由于 if 模块中的 return 语句没有显式表达式,因此违反了规则。

检查信息

组:函数
类别:强制
AGC 类别:强制

版本历史记录

在 R2014b 中推出

全部展开


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.