【问题标题】:Keep getting error message not all control paths return a value不断收到错误消息并非所有控制路径都返回值
【发布时间】:2020-08-31 10:41:45
【问题描述】:
bool isEnemy(const string& check) {
  if (check == enemy1 || check == enemy2 ||
      check == enemy3)  // if the name being checked is an enemy of this knight
    return true;
  else
    return false;
}

int Canidate(Knight b) {  //'b' is an enemy of 'a' who is in the seat before
                          //'b'(ie. b seat=2 a seat=1
  int toSwap = b.seatingPos;  // toSwap holds seating pos # of 'b'
  int checkFriends = (toSwap - 1);  // holds seating pos of 'a'
  for (int i = 0; i < 8; i++) {
    if (!(table[i].isEnemy(table[checkFriends].getName())))  // if not enemies,
                                                             // then must be
                                                             // friends
    {
      friends.push_back(table[i].seatingPos);  // adds seating # of friends of
                                               // 'a' to friends vector
    }
  }
  for (int j = 0; j < 3; j++) {  // check friends of 'a' to see if their
                                 // neighbor is friends with 'b'
    int check2 =
        table[friends[j]].seatingPos;  // check 2 holds seating pos # of 'c'
    if (!(table[toSwap].isEnemy(
            table[(friends[j] + 1)]
                .getName()))) {  // if neighbor of c is friends with b(toSwap)
      return check2;  // if not enemies then must be friends return seating pos
                      // of acceptable canidate
    }
  }
}

tablevector&lt;Knight&gt;friendsvector&lt;int&gt;

【问题讨论】:

  • 假设你的最后一个 for 循环一直运行而没有返回,那么你的函数返回什么值?
  • 你的函数,很明显,如果你的循环没有被输入,或者它们返回的条件从未满足,你的函数不会返回任何东西。
  • 在例程结束时,要么执行return -1;(或任何在您的程序中有意义的标记值),要么执行throw std::runtime_error("never supposed to get here");
  • 明白了,返回-1,解决了不是所有路径都返回值的问题。显然我的函数也使我的向量下标超出范围,我看看我是否能弄清楚为什么会发生这种情况。感谢您抽出宝贵时间

标签: c++ c++11 if-statement vector conditional-statements


【解决方案1】:

当您的函数有一种方法可以跳过您指定返回的情况时,就会出现这个问题。

这是一个例子:

int funct() {
    int a = 3;
    if(a == 4) {
        return a;
    }
}

如果“a”是 4,那么我们就知道要返回什么。但是如果“a”不是 4,函数不知道返回什么。要更正此问题,您需要为函数提供一个 return 语句,该语句将涵盖其余可能的情况。

int funct() {
    int a = 3;
    if(a == 4) {
        return a;
    }
    return -1;
}

这样,函数可以采用的所有路径都已被覆盖,并且函数知道如果“a”不等于 4 会返回什么。

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 2014-09-22
    • 1970-01-01
    相关资源
    最近更新 更多