Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Recursion stopping condition

  1. Mar 3, 2007 #1

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    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!
     
  2. jcsd
  3. Mar 3, 2007 #2

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    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;
    }
     
  4. Mar 3, 2007 #3

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks, AZ!
     
  5. Mar 3, 2007 #4
    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.
     
  6. Mar 3, 2007 #5

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    For example,
    Code (Text):
    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 (Text):
    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.
     
  7. Mar 3, 2007 #6
    Sure. Either way. Depends on style and acceptance.
     
  8. Mar 3, 2007 #7

    verty

    User Avatar
    Homework Helper

    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.
     
  9. Mar 4, 2007 #8

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks for your advice on this, everyone. I appreciate it.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Recursion stopping condition
  1. Recursion in C (Replies: 12)

Loading...