Main Content

MISRA C:2023 Rule 17.4

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

Since R2024a

Description

Rule Definition

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

Rationale

If a non-void function does not explicitly return a value but the calling function uses the return value, the behavior is undefined. To prevent this behavior:

  • You must provide return statements with an explicit expression.

  • You must ensure that during run time, at least one return statement executes.

As an exception, lacking an explicit return statement in your main() function is compliant with this rule if you use C99 or later.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

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


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

In this example, the function absolute violates this rule because the execution path where v >= 0 does not have a return statement. Because this rule does not require an explicit return statement in the main() function, Polyspace® does not report any violation in the main() function.

#define SIZE 10
int table[SIZE];

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

In this example, the rule is violated because the return statement in the if block does not have an explicit expression.

Check Information

Group: Function
Category: Mandatory
AGC Category: Mandatory

Version History

Introduced in R2024a