Why compile error “Use of unassigned local variable”?

前端 未结 10 2315
说谎
说谎 2020-11-22 03:16

My code is the following

int tmpCnt;  
if (name == \"Dude\")  
   tmpCnt++;  

Why is there an error Use of unassigned local variabl

10条回答
  •  悲哀的现实
    2020-11-22 03:58

    A very dummy mistake but you can get this with a class too if you didn't instantiate it.

    BankAccount account;
    account.addMoney(5);
    

    The above will produce the same error where as:

    class BankAccount
    {
        int balance = 0;
        public void addMoney(int amount)
        {
            balance += amount;
        }
    }
    

    Do the following to eliminate the error

    BankAccount account = new BankAccount();
    account.addMoney(5);
    

提交回复
热议问题