Why compile error “Use of unassigned local variable”?

前端 未结 10 2317
说谎
说谎 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 04:09

    Local variables are not automatically initialized. That only happens with instance-level variables.

    You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the new operator.

    The code you've shown does indeed attempt to use the value of the variable tmpCnt before it is initialized to anything, and the compiler rightly warns about it.

提交回复
热议问题