Main Content

Return value not initialized

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 every function call.

Examples

expand all

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

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

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

In this example, for the function call reply(0), there is no return value. Therefore the Return value not initialized check returns a red error. The second call reply(ch) always returns a value. Therefore, the check on this call is green.

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(0);
  else
    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 Return value not initialized check returns an orange error on reply(ch).

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: Data flow
Language: C
Acronym: IRV