+ 3

How the following program works?

#include <stdio.h> int foo(int x,int n) { int val; val=1; if (n>0) { if(n%2 == 0) val=val*x; val=val*foo(x*x,n/2); return; } } int main() { int r; r=foo(2,4); printf("%d",r); }

23rd Aug 2019, 4:31 PM
Prabakaran
Prabakaran - avatar
10 Réponses
+ 3
This returns 2048 . Why it happens?
23rd Aug 2019, 4:32 PM
Prabakaran
Prabakaran - avatar
+ 3
Remember that val is changed in the recursive foo call. So eventually, what's returned will be an a*b*c*d... thing. Different result on Linux? Strange! Maybe we should ask someone like ~ swim ~ who *will* have the answer...
23rd Aug 2019, 5:43 PM
HonFu
HonFu - avatar
+ 2
If not return statrment means, which value is actually return .... ??
23rd Aug 2019, 4:39 PM
Er.Muthukumar
Er.Muthukumar - avatar
+ 2
HonFu [#GoGetThatBugChamp!] No,if return is (return Val )means final recursion stage Val variable contains 1 so the output will be vary but here the program output is 2048 in sololearn compiler and in Linux : 4096
23rd Aug 2019, 4:46 PM
Er.Muthukumar
Er.Muthukumar - avatar
+ 2
but ~ swim ~ the function should at least return a value, and the value needed to be return is val
23rd Aug 2019, 8:41 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 1
Seems like it's val, which is declared first. You can change the return to return val, and the result is the same.
23rd Aug 2019, 4:41 PM
HonFu
HonFu - avatar
0
Output comes same value in Everytime. But garbage not come every time same value
24th Aug 2019, 11:26 AM
Er.Muthukumar
Er.Muthukumar - avatar