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

时间:2013-11-25 10:05:59

标签: c++ recursion

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

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

所以我控制台检查发生了什么,然后它返回一个值,但当我转到主要功能cout时它什么都不返回。

2 个答案:

答案 0 :(得分:3)

好吧,你没有从递归调用返回值给调用者:

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

返回

想象一下,您是从主要功能输入代码,并且在else的第一次通话中您将进入decodeFile分支,这将再次呼叫decodeFile

main -> decodeFile -> decodeFile

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

main (NO RETURN)  decodeFile <- decodeFile

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

答案 1 :(得分:0)

您的功能未能return分支else部分内的任何内容。

如果您正在使用gcc,则可以让编译器使用-Wreturn-type-Wall选项向您发出有关此类情况的警告。