当我在递归函数中调用 return 时,我的程序意外完成



我有一个递归函数,它遍历二叉树并在节点到达叶节点时返回节点的值,但我的程序在返回调用时意外完成。这是我的代码:

string decodeFile(int cha, ibitstream& input, HuffmanNode* encodingTree, HuffmanNode*& root, string& result) {
  if(root->isLeaf()) {
    char value = root->character;
    string temp(1,value);
    cout << temp << endl;
    return temp;
  } else {
    if(cha == 0) root = root->zero;
    if(cha == 1) root = root->one;
    decodeFile(input.readBit(), input, encodingTree, root, result);
  }
}

所以我控制台检查发生了什么,此时它返回一个值,但当我转到 main 函数进行 cout 时,它什么也没返回。

好吧,您不会从对调用方的递归调用中返回值:

string decodeFile(int cha, ibitstream& input, HuffmanNode* encodingTree, HuffmanNode*& root, string& result) {
if(root->isLeaf()) {
    char value = root->character;
    string temp(1,value);
    cout << temp << endl;
    return temp;
} else {
    if(cha == 0) root = root->zero;
    if(cha == 1) root = root->one;
    // do calculation and return result!
    return decodeFile(input.readBit(), input, encodingTree, root, result);
}

它是一个字符串类型,所以我将值作为字符串 temp 返回

想象一下,您正在从 main 函数输入代码,并且在第一次调用decodeFile时进入else分支,该分支将再次调用decodeFile

main -> decodeFile -> decodeFile

现在,第二个decodeFile返回带有 return temp 的值,但第一个decodeFile没有向 main 函数返回任何内容(因为它在调用 decodeFile 后退出(:

main (NO RETURN)  decodeFile <- decodeFile

为了避免此类错误,请侦听 Riot 并向编译器添加其他警告标志。

您的函数无法在分支的else部分中return任何内容。

如果您使用的是 gcc,则可以让编译器使用 -Wreturn-type-Wall 选项警告您此类情况。

最新更新