30th Jan 2022, 3:50 PM
Suresh Rajendiran
6 odpowiedzi
+ 1
It has to do with the calls to fun. The lines 6 - 9 are being dismissed as they stack up on the "stack" and therefore the outcome of the original call is 33 when x = 0.
30th Jan 2022, 5:52 PM
William Owens
William Owens - avatar
0
Very interesting, I do not know the answer. I would calculate Z to equal 4 on the 7th pass of fun. changing a and b to the respective x, y 1st pass x = 13, y = 7 --> fun(x++-1, ++y+1) 2nd pass x = 12, y = 9 --> fun(x/2, y/2) 3rd pass x = 6, y = 4 --> fun(x/2, y/2) 4th pass x = 3, y = 2 --> fun(x++-1, ++y+1) 5th pass x = 2, y = 4 --> fun(x/2, y/2) 6th pass x = 1, y = 2 --> fun(x/2, y/2) 7th pass x = 0, y = 4 --> return y for some reason when I ran it on GDB the 7th pass went to fun(x++-1, ++y+1) after the return b statement
30th Jan 2022, 4:49 PM
William Owens
William Owens - avatar
0
William Owens Thanks for the clarification
30th Jan 2022, 5:57 PM
Suresh Rajendiran
0
Suresh Rajendiran this is an extremely inefficient function to calculate b+2*a. In the middle of the function it performs unnecessary recursion without using the return value. And it modifies a and b without using them afterward. By cutting out those inefficiencies and reducing, we get: int fun(int a, int b) { return a? fun(a-1, b+2) : b; } Now it becomes clearer that a simply iterates down to 0 as b increments by 2. The result is to add 2 to b, a times; more simply, b+2*a. Try a=13, b=7: 7+2*13 = 7+26 = 33.
30th Jan 2022, 6:27 PM
Brian
Brian - avatar
0
Brian - I think that was the point of the code someone wrote. To show how the fiction builds up on the stack during recuse. Not 100 percent sure though.
30th Jan 2022, 10:26 PM
William Owens
William Owens - avatar
0
Hi William Owens. Somehow when I first viewed this question, and even refreshed a few times, there were no replies before I responded. But now I see there were a couple exchanges already that didn't appear until now. Regarding the code, I agree that it may have an educational origin, not to be viewed as an example of good programming. Because it does tail recursion, I had considered also pointing out how easy it would be to convert into a loop for more efficiency. Though when I realized that it was a simple expression implemented in an impractical way, that edified for me the notion that it was educational. So I decided to leave my final code in recursion form and let the OP study it in context of recursion. When I am employed, I usually work with legacy code, and I do enjoy streamlining code like this after several generations of developers have added their tweaks without regard to the whole context.
31st Jan 2022, 3:39 AM
Brian
Brian - avatar