I am doing a book exercise regarding the Ackermann function.
I have one question though. If I declare result but do not initialise it, the compiler complains that “variable result might not have been initialised”.
int result;
When I set it to default to 0, it does not complain.
int result = 0;
I thought that when one declares a variable with type int it defaults to 0 automatically.
Here’s the complete code:
public class Ackermann {
public static int ack(int m, int n) {
int result = 0;
//int result;
if (m == 0)
result = n + 1;
else if(m > 0 && n == 0)
result = ack(m-1, 1);
else if(m > 0 && n > 0)
result = ack(m-1, ack(m, n-1));
return result;
}
public static void main(String[] args) {
System.out.println(ack(3, 3));
}
}
Local variables are not initialized with default values. See the language specs for the ground truth.