Reputation: 2410
I have a function that needs to return a value when it's done doing some stuff. I won't bore you with the details. My function calls itself so it's recursive. Now, I want to be able to obtain the resulting value of this function when I call it from elswhere. So this is the code:
public int compute(string[] myarray)
{
if (hasParantesisBlock)
{
// do stuff
// remove paranthesis block from myarray
String[] newArray = removeBlockFromArray(myarray);
// recursive call
compute(newArray);
}
else
{
// do other stuff obtaining a value
return value;
}
return 0; // if I remove this I get error
}
and I call it like this:
int myval = compute(myStringArray);
I have a string array and I want to remove blocks that are between parentheses from this myStringArray. I do that in my function compute, until there are no more parentheses blocks there. When that happens I want to do a count of the elements of the string array for example (not a good example) and I want to return that value in the main code.
Because of that last "return 0; ", I always receive 0. But if I display the result (value) from inside the recursive method... I get the right value.
And if there are 2 blocks of parentheses in my string array, then I will get 2 returned values of ZERO, if I have 3 blocks, then I will get 3 ZERO results....
I do not want those ZERO results. I only want to return the value obtained when there are no blocks left in the string Array.
So steps are like this:
- does it have a block?
- yes. remove block and recall with changed array
- does it have a block?
- yes. remove block and recall with changed array
- does it have a block?
- no. RETURN my value (!!! this is the only return I want to receive)
- standard return
- standard return
How can I do that?
Upvotes: 0
Views: 280
Reputation: 173
As Peter said,
remove the return 0; return the value of compute(newArray) instead.
(can't comment as i don't have enough rep).
public int compute(string[] myarray)
{
if (hasParantesisBlock)
{
// do stuff
// remove paranthesis block from myarray
String[] newArray = removeBlockFromArray(myarray);
// recursive call
return compute(newArray);
}
else
{
// do other stuff obtaining a value
return value;
}
}
without viewing the entire code i can see a few possible gotchas. Such as not using the return value in the method. As in
return compute(newArray)++;
Upvotes: 2