Main Content

Number of return statements exceeds threshold

The number of return statements in a function is greater than the defined threshold

Since R2021a

Description

This defect is raised on a function when the number of return statement in the function is greater than the defined checker threshold. For details about how Polyspace calculates the number of return statements in a function, see Number of Return Statements

Polyspace® uses the default threshold 1 unless you specify a threshold. To specify a selection file where you can set the threshold, use the option Set checkers by file (-checkers-selection-file) or Checkers activation file (-checkers-activation-file).

When you import comments from previous analyses by using polyspace-comments-import, Polyspace copies any review information on the code metric Number of Return Statements in the previous result to this checker in the current result. If the current result contains the same code metric, the review information is copied to the code metric as well.

Risk

Having multiple return statements makes it difficult to determine what object a function might return. Such confusion might lead to bugs and maintenance issues that are difficult to debug.

Fix

To fix this check, use a single return statement. For instance, store the return value in an object and define it conditionally instead of returning different objects in different conditionalized return statement.

Examples

expand all

int afunc (int x);
int foo2(int x,int y)//Noncompliant 
{
	
	if (x <= 0){
		if (x > 10 ) { return 0; }
	}
	if (x<-240) {
		if (x < -2565) { 
			return (x < -253 ? 0: afunc (x <22566 ? 1: afunc(x < -25103 ? 0: 6))); 
		}
	}
}

In this example, the return statement of foo is conditionalized, leading to two return statements, which exceeds the default return statement threshold of one. Polyspace flags the function foo as noncompliant.

Correction — Declare Object to Store Return value

One possible correction is to declare an object which is then conditionally defined to have the appropriate return value. This object is then returned by the function by using a single return statement.

int afunc (int x);
int foo2(int x,int y)//Compliant 
{
	int returnData;
	if (x <= 0){
		if (x > 10 ) { returnData =  0; }
	}
	if (x<-240) {
		if (x < -2565) { 
			returnData =  (x < -253 ? 0: afunc (x <22566 ? 1: afunc(x < -25103 ? 0: 6))); 
		}
	}
	return returnData;
}

Check Information

Group: Software Complexity
Language: C | C++
Acronym: SC16
Default Threshold: 1

Version History

Introduced in R2021a