when I remove return in else section the code throw word.exe has stopped working I tried to debug and when the base condition is true and 'i' start to decrement when 'i' is equal to 1 it throws the error
string o = "555";
string play(int i){
if(i == 3) return o;
else
return play(i+1);
}
You cannot remove the return
statement.
Indeed, play()
returns a string
. So if the condition is true
, you return the string
o
. But if you enter the else block, you also have to return a string
, because the play(i+1)
will return a string if its condition succeed, but nothing otherwise (except running another call). And you don't want to get nothing, you want to get back the resulting string
.
In other words, when the child function returns a string
, the current function needs to pass it to its parent and so on . If the child function condition succeeds and you missed the return statement, you will never pass this result to the parent and finally, you will return nothing at the top (Unexpected behaviour or error, honestly I didn't try).
And by the way, the code you are running is very dangerous. If the int
passed in parameter is greater than 3
, the recursion will run endlessly, adding play()
calls until running out of memory.
I hope it answers your question :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.