Here is your function (not program, function), formatted so it's easier to read:
1 2 3 4 5 6 7 8 9
|
unsigned int f1 (unsigned int a, unsigned int b)
{
if (a == 0)
return b;
else if (b == 0)
return a;
else
return f1 (a, b-1) + b;
}
|
Oh no, I hate function recursion...
At least, that's what this looks like. Where the function calls itself, and then you have a whole lovely loop of junk going back and forth until you can't tell which is which.
It's like looking in a mirror with another mirror behind you, and you can just keep looking at yourself looking in a mirror at yourself looking in a mirror at yourself looking in a mirror...Ugh.
So, if you call the function in main (or in another function), e.g.
|
unsigned number = f1 (3, 6);
|
then what it does is
1. It passes 3 and 6 to the function
2. The function reads the numbers, and neither "a" nor "b" == 0
3. So it goes to the "else"
4. And calls itself, passing 3 and 5
5. Then it does steps 2 and 3 again
6. And calls itself, passing 3 and 4 this time.
7. Then it goes on, and on, and on, and on for all of bloody eternity.
I'm actually getting a headache just trying to figure out how in the heck this even works.
Unless the
unsigned return type has something to do with it. Maybe it stops it somewhere along the way; when "b" reaches 0 or something like that.
Edit:
@lastchance,
Yeah, something like that. Just ran it in my debugger using step-in, and that's what it looks like it does. Goes through it a bunch of times and then returns b = 0, so then it returns a, and does a bunch of other stuff that I didn't understand, and output 24.
Sorry about the rant, I just don't like recursive functions because of the repeating aspect. It's just confusing (and it can be very easy to get an infinite running if you do something wrong).