Recursion

closed account (10oTURfi)
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
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
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
closed account (10oTURfi)
@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
@rambo1177
Recursion is ok when appropriate. goto is never ok.

@Krofna
Your solution should work even without return
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.
closed account (1vRz3TCk)
... goto is never ok.
Always and never rules are never correct and should always be avoided. ;0)
Always and never rules are never correct and should always be avoided.


Excellent quote. Gonna save that one :)
Topic archived. No new replies allowed.