user4011744
user4011744

Reputation: 13

Short circuit recursion

Is it possible to do the following without getting a stackoverflow?

int foo(int i = 0)
{
    return foo(--i) || i;
}

When foo(--i) evaluates to 0, it should return false, therefore returning i and ending the execution.

Upvotes: 0

Views: 728

Answers (2)

Suvarna Pattayil
Suvarna Pattayil

Reputation: 5239

From what you have coded foo never returns because it will continuosly go on decreasing i and recurse. You need a check inside foo which returns whatever you want when you get i as 0.

Upvotes: -1

Bathsheba
Bathsheba

Reputation: 234685

You want return !i || foo(--i).

Note that || is short-circutted. This means that evaluation (which is performed from left to right) will continue for only as long as the result of the expression is not known. So the way I've written it, the case i being zero will block the recursion.

(Moving on to more advanced issues, you need to be very careful when evaluating expressions when the same variable appears in more than one sub-expression and it's value is changed in some of them. My having !i and --i could get me in trouble: I'm not too far away from undefined behaviour here. In fact, it turns out that my code is completely safe since || is a sequence point and the order of evaluation with || is well-defined. But do be careful.)

Upvotes: 4

Related Questions