Missing return statement

Function does not return value though return type is not void

Description

This defect occurs when a function does not return a value along at least one execution path. This defect does not occur if:

  • The return type of the function is void.

  • The execution path is terminated by a function that does not return the flow of execution, such as a [[noreturn]] function.

Risk

If a function has a non-void return value in its signature, it is expected to return a value. The return value of this function can be used in later computations. If the execution of the function body goes through a path where a return statement is missing, the function return value is indeterminate. Computations with this return value can lead to unpredictable results.

Fix

In most cases, you can fix this defect by placing the return statement at the end of the function body. If your code has execution paths that do not return the flow of execution, specify them by using the attribute [[noreturn]].

Alternatively, you can identify which execution paths through the function body do not have a return statement and add a return statement on those paths. Often the result details show a sequence of events that indicate this execution path. You can add a return statement at an appropriate point in the path. If the result details do not show the event history, you can trace back using right-click options in the source code and see previous related events. See also Interpret Bug Finder Results in Polyspace Desktop User Interface.

See examples of fixes below.

If you do not want to fix the issue, add comments to your result or code to avoid another review. See Address Polyspace Results Through Bug Fixes or Justifications.

If the analysis flags a missing return statement on a path where a process termination function exists, you can make the analysis aware of the process termination function using the option -termination-functions.

Examples

expand all

int AddSquares(int n)
 {
   int i=0;
   int sum=0;
   
   if(n!=0) 
    {
     for(i=1;i<=n;i++)
        {
         sum+=i^2;
        }
     return(sum);
    }
 } 
/* Defect: No return value if n is not 0*/

If n is equal to 0, the code does not enter the if statement. Therefore, the function AddSquares does not return a value if n is 0.

Correction — Place Return Statement on Every Execution Path

One possible correction is to return a value in every branch of the if...else statement.

 int AddSquares(int n)
 {
   int i=0;
   int sum=0;
   
   if(n!=0) 
    {
     for(i=1;i<=n;i++)
        {
         sum+=i^2;
        }
     return(sum);
    } 
   
   /*Fix: Place a return statement on branches of if-else */
   else 
     return 0;  
  }

Result Information

Group: Data flow
Language: C | C++
Default: On
Command-Line Syntax: MISSING_RETURN
Impact: Low
Introduced in R2013b