Main Content

MISRA C++:2023 Rule 9.6.4

A function declared with the [[noreturn]] attribute shall not return

Since R2024b

Description

Rule Definition

A function declared with the [[noreturn]] attribute shall not return.

Rationale

If you declare a function by using the [[noreturn]] attribute, the compiler expects that the function does not return the flow of execution. That is, if a [[noreturn]] function f() is called from main(), then the compiler expects that the flow of execution is not returned to main(). If such a function eventually returns the flow of execution, it leads to undefined behavior, which can be exploited to cause data integrity violations.

If a function has no return statement, then the final closing brace of a function implies an implicit return. Omitting a return statement in the function does not prevent the flow of execution from returning. A [[noreturn]] function can prohibit returning the flow of execution to the calling function by:

  • Entering an infinite loop

  • Raising an exception

  • Calling another [[noreturn]] function

Polyspace Implementation

If a function specified as [[noreturn]] returns the control flow to its caller, Polyspace® flags the [[noreturn]] function.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

Consider this code containing two [[noreturn]] functions.

#include <iostream>

[[noreturn]] void noncompliant(int i)
{
	if (i > 0)
	throw "Received positive input";
	else if (i < 0)
	std::exit(0);
} //Noncompliant
[[noreturn]] void compliant(int i)
{
	if (i > 0)
	throw "Received positive input";
	else if (i < 0)
	std::exit(0);
	else if(i==0)
	while(true){
		//...
	}
}//Compliant
  • In the noncompliant() function, the flow of execution skips the if-else-if block of code and returns to the caller implicitly if i == 0. Because the [[noreturn]] function returns the flow of execution in a code path, this function is noncompliant with this rule.

  • In the compliant() function:

    • The function raises an exception if i > 0.

    • The function calls the [[noreturn]] function std::exit() if i < 0.

    • The function enters an infinite loop if i==0.

    Because the [[noreturn]] function does not return the flow of execution in any code path, it is compliant with this rule.

Check Information

Group: Statements
Category: Required

Version History

Introduced in R2024b