主要内容

未返回值的函数

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

描述

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

示例

全部展开

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

在此示例中,对于 ch 的所有值,reply(ch) 都没有返回值。因此,未返回值的函数检查在 reply() 的定义上返回了一个红色错误。

更正 - 为所有输入返回值

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

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

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

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

因此,未返回值的函数检查在 reply() 的定义上返回了一个橙色错误。

更正 - 为所有输入返回值

一种可能的更正方法是为 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++
语言:C++
缩写:FRV