Reputation: 31
I came across this code, but I couldn't understand how the recursion works for the following code, as there's a Boolean OR operator used within a return
statement, which I have never seen before. How is it supposed to work?
bool match(char *first, char * second)
{
if (*first == '\0' && *second == '\0')
return true;
if (*first == '*' && *(first+1) != '\0' && *second == '\0')
return false;
if (*first == '?' || *first == *second)
return match(first+1, second+1);
if (*first == '*')
return match(first+1, second) || match(first, second+1); //How does it work?
return false;
}
Upvotes: 0
Views: 106
Reputation: 66441
It works like all other disjunctions:
First the left-hand side, match(first+1, second)
is evaluated.
If it is true
, the result of the entire expression is true
and nothing else is evaluated.
If it is false
, the right-hand side, match(first, second+1)
is evaluated and that becomes the result of the entire expression.
Upvotes: 4
Reputation: 12047
An important feature of the boolean operators ||
and &&
is short-circuit evaluation. That means in the case of ||
that if the first call match(first + 1, second)
returns true
, the second call will not be made, and true
will be returned. Else the return value is the returned value of the second call.
Upvotes: 1
Reputation: 10880
It works mostly as if a variable were assigned the parameter of return
, then that variable returned. The only difference is, the compiler might do return value optimization.
Upvotes: 0