主要内容

返回值未初始化

C 函数在预期应返回值时未返回值

描述

此检查用于确定返回类型不是 void 的函数是否返回了值。此检查出现在每个函数调用处。

示例

全部展开

#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);
}

在此示例中,对于函数调用 reply(0),没有返回值。因此,返回值未初始化检查返回红色错误。第二个调用 reply(ch) 始终返回值。因此,针对此调用的检查为绿色。

更正 - 为所有输入返回值

一种可能的更正方法是为 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);
}

在此示例中,在 if 语句的第一个分支内,ch 的值可划分为两个范围:

  • ch < = 0:对于函数调用 reply(ch),没有返回值。

  • ch > 0ch < 10:对于函数调用 reply(ch),有返回值。

因此,返回值未初始化检查针对 reply(ch) 返回橙色错误。

更正 - 为所有输入返回值

一种可能的更正方法是为 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);
}

检查信息

组:数据流
语言:C
缩写:IRV