How the following program works? | SoloLearn: Learn to code for FREE!

+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); }

8/23/2019 4:31:50 PM

Prabakaran

10 Answers

New Answer

+4

Undefined behaviour. I get this error when trying to compile with clang: error: non-void function 'foo' should return a value --- From the C documentation: "If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined." --- To prove this I've modified your code a little for testing with different inputs: https://code.sololearn.com/ccuyAsQ9jNF3/?ref=app

+4

@HonFu [#GoGetThatBugChamp!] Thanks for mentioning. Er.Muthukumar The result value can be in eax register, but may not be the case on different platforms. What you are getting is garbage value. I think with current Standards, the results are undefined.

+3

This returns 2048 . Why it happens?

+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...

+2

If not return statrment means, which value is actually return .... ??

+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

+2

but ~ swim ~ the function should at least return a value, and the value needed to be return is val

+2

✳AsterisK✳ The function is returning a value and it is garbage value since there is no explicit value being returned.

+1

Seems like it's val, which is declared first. You can change the return to return val, and the result is the same.

0

Output comes same value in Everytime. But garbage not come every time same value