Recursion stopping condition

  • #1
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
4,527
28
I just finished writing a little recursive function in C++ and when my stopping condition is reached, I need it to do nothing. So the if statement looks funny:

if (the condition is met)
{
//do nothing
}
else
{
call yourself with smaller arguments
}

It works fine, but I feel uneasy about having absolutely nothing in the
if{} portion.
Is this bad programming style? Is it potentially dangerous?
Thanks!
 

Answers and Replies

  • #2
AlephZero
Science Advisor
Homework Helper
6,994
292
IMO the original is OK - the //do nothing comment makes it clear it means what it says.

You could write

if (! the condition is met)
{
do something;
}

Or possibly

if (the condition is met)
return;
else
{
do something;
}
 
  • #3
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
4,527
28
Thanks, AZ!
 
  • #4
254
0
I just finished writing a little recursive function in C++ and when my stopping condition is reached, I need it to do nothing. So the if statement looks funny:

if (the condition is met)
{
//do nothing
}
else
{
call yourself with smaller arguments
}

It works fine, but I feel uneasy about having absolutely nothing in the
if{} portion.
Is this bad programming style? Is it potentially dangerous?
Thanks!
It might be better for you to make your recurrence condition slightly different, so that you don't even need an else statement. That way both the 'if' and the 'else' statements can have a purpose, you might not even need the else statement.
 
  • #5
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
685
It might be better for you to make your recurrence condition slightly different, so that you don't even need an else statement.
For example,
Code:
if (! done) {
   do_something_recursively;
}
However, in some circles that place an emphasis on high-quality programming, the lack of an else is seen as a sign that something may be awry. If no else is needed, such programmers would write the above as
Code:
if (! done) {
   do_something_recursively;
} else {
   ; /* Null else */
}
to show that the algorithm designer/programmer has indeed deemed that no else is needed rather than merely forgotten.
 
  • #6
254
0
Sure. Either way. Depends on style and acceptance.
 
  • #7
verty
Homework Helper
2,164
198
I like to have the exit cases before the recursive ones, so for me the original is perfect, just how I would have done it.
 
  • #8
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
4,527
28
Thanks for your advice on this, everyone. I appreciate it.
 

Related Threads on Recursion stopping condition

  • Last Post
Replies
8
Views
923
  • Last Post
Replies
5
Views
906
  • Last Post
Replies
12
Views
80K
  • Last Post
Replies
13
Views
995
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
16
Views
3K
  • Last Post
Replies
8
Views
6K
  • Last Post
Replies
0
Views
1K
  • Last Post
Replies
1
Views
768
Top