Main Content

Function not returning value

C++ function does not return value when expected

Description

This check determines whether a function with a return type other than void returns a value. This check appears on the function definition.

Examples

expand all

#include <stdio.h>
int input();
int inputRep();

int reply(int msg) {
  int rep = inputRep();
  if (msg > 0) return rep;
}

void main(void) {
  int ch = input(), ans;
  if (ch<=0)
    ans = reply(ch); 
  printf("The answer is %d.",ans);
}

In this example, for all values of ch, reply(ch) has no return value. Therefore the Function not returning value check returns a red error on the definition of reply().

Correction — Return value for all inputs

One possible correction is to return a value for all inputs to reply().

#include <stdio.h>
int input();
int inputRep();

int reply(int msg) {
  int rep = inputRep();
  if (msg > 0) return rep;
  return 0;
}

void main(void) {
  int ch = input(), ans;
  if (ch<=0)
    ans = reply(ch); 
  printf("The answer is %d.",ans);
}
#include <stdio.h>
int input();
int inputRep(int);

int reply(int msg) {
  int rep = inputRep(msg);
  if (msg > 0) return rep;
}

void main(void) {
  int ch = input(), ans;
  if (ch<10)
    ans = reply(ch); 
  else
    ans = reply(10);
  printf("The answer is %d.",ans);
}

In this example, in the first branch of the if statement, the value of ch can be divided into two ranges:

  • ch < = 0: For the function call reply(ch), there is no return value.

  • ch > 0 and ch < 10: For the function call reply(ch), there is a return value.

Therefore the Function not returning value check returns an orange error on the definition of reply().

Correction — Return value for all inputs

One possible correction is to return a value for all inputs to reply().

#include <stdio.h>
int input();
int inputRep(int);

int reply(int msg) {
  int rep = inputRep(msg);
  if (msg > 0) return rep;
  return 0;
}

void main(void) {
  int ch = input(), ans;
  if (ch<10)
    ans = reply(ch); 
  else
    ans = reply(10);
  printf("The answer is %d.",ans);
}

Check Information

Group: C++
Language: C++
Acronym: FRV