This is regarding another question: Java Recursion Bug? I am going crazy.
I understand the solution there. But, why does C++ behaves differently than Java in this case?
Can anybody please give exact pointers (no pun) to C++/Java specifications? I know that java assigns 0 to sum before each call, while C++ does it differently. But what's the specification which allows this?
Edit: Adding code from link
public class Test {
public static int sum=0;
public static int fun(int n) {
if (n == 1)
return 1;
else
sum += fun(n - 1); // this statement leads to weird output
// { // the following block has right output
// int tmp = fun(n - 1);
// sum += tmp;
// }
return sum;
}
public static void main(String[] arg) {
System.out.print(fun(5));
}
}
The output is 1 which should be 8. Relative C/C++ code is as follows:
#include<stdio.h>
int sum=0;
int fun(int n) {
if (n == 1)
return 1;
else
sum += fun(n - 1);
return sum;
}
int main()
{
printf("%d",fun(5));
return 0;
}
Output in C++ is 8
.