开发者

Error: variable might not have been initialised

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.


it is very bad practice to not initialize variables. There is popular joke that fits to your case: John got 3 apples from his mother and 5 from his father. How many apples has John? If you are not good programmer, your answer will be 8. If you are good programmer, you will answer that we do not know how many apples had had john before obtaining apples from his Mother. Remember: always initialize variables and do not assume that they will be 0.


Fields in classes default to values (null, 0, false, etc.) Local variables however don't, you have to define them explicitly. A lot of people even disagree with not setting fields explicitly, because setting it shows the reader that you've actually thought about setting it to a value rather than just forgotten to set it, therefore potentially causing a bug somewhere down the line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜