Reputation: 1
I have this recursive function which traverses a binary tree and returns the value of the node when it gets to a node that is leaf but my program unexpectedly finishes at the return call. Here is my code:
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);
}
}
so I console out to check what is happening and at that point it returns a value but when i go to the main function to cout it returns nothing.
Upvotes: 0
Views: 98
Reputation: 22157
Well, you're not returning value from the recursive call to the caller:
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);
}
its a string type so i return the value as a string temp
Imagine that you're entering your code from main function and that you're going into else
branch in the first call of decodeFile
which will call decodeFile
again:
main -> decodeFile -> decodeFile
Now, the second decodeFile
is returning value with return temp
, but the first decodeFile
is not returning anything to the main
function (as it is exiting after call to decodeFile
):
main (NO RETURN) decodeFile <- decodeFile
In order to avoid these kind of errors, listen Riot and add additional warning flags to your compiler.
Upvotes: 3
Reputation: 16706
Your function is failing to return
anything in the else
portion of the branch.
If you're using gcc, you can get your compiler to warn you about such cases using the -Wreturn-type
or -Wall
options.
Upvotes: 0