Recursion
Aug 23, 2011 at 8:23pm UTC
So... program leaves void function when } is encountered, but how do I exit it BEFORE }?
1 2 3 4 5 6
void myfunc(int a){
a++;
cout << a << endl;
if (a==10)//This is where I want recursion to end.
myfunc(a);
}
Do I really have to use int return type function if I want to do that? (assuming that
return 0;
would be best way to do that)
Last edited on Aug 23, 2011 at 8:26pm UTC
Aug 23, 2011 at 8:28pm UTC
To exit a function, you use return. if the function return type is void, then you don't have to return anything:
1 2 3
if (a == 10)
return ; // this will work just fine
myfunc(a);
Last edited on Aug 23, 2011 at 8:28pm UTC
Aug 24, 2011 at 1:33am UTC
1 2 3 4 5 6 7
void myfunc(int a){
a++;
cout << a << endl;
if (a==10)goto functionend;
myfunc(a);
functionend:
}
Moreover calling a function within itself is bad coding..
1 2 3 4 5 6 7 8 9 10
void myfunc(int a){
cout << a << endl;
functionend:
}
void myotherfunc()
{
int i;
for (i=0;i<10;i++)
{myfunc(i);}
}
@Disch : The function is of type void ( non returning ) and so it would throw error if you ask it to return a value
Aug 24, 2011 at 1:12pm UTC
@Disch Thanks! It worked fine.
@rambo1177
Actually in Mastery Check of CH5 C++ Beginner's Guide I am reading, task 10 asked me to make recursion
Aug 24, 2011 at 1:38pm UTC
@rambo1177
Recursion is ok when appropriate. goto
is never ok.
@Krofna
Your solution should work even without return
Aug 24, 2011 at 1:48pm UTC
Moreover calling a function within itself is bad coding..
No it's not, that's how recursion works. Recursion may not always be the best solution, however sometimes it just makes sense. e.g. when traversing tree structures. As coder777 said, recursion is ok when appropriate.
@Disch : The function is of type void ( non returning ) and so it would throw error if you ask it to return a value
But Disch wasn't returning a value. Calling
return ;
from within a void function is perfectly valid.
Aug 24, 2011 at 2:00pm UTC
Always and
never rules are
never correct and should
always be avoided. ;0)
Aug 24, 2011 at 11:04pm UTC
Always and never rules are never correct and should always be avoided.
Excellent quote. Gonna save that one :)
Topic archived. No new replies allowed.