Program Club

왜 "할당되지 않은 로컬 변수 사용"오류를 컴파일합니까?

proclub 2020. 12. 3. 20:47
반응형

왜 "할당되지 않은 로컬 변수 사용"오류를 컴파일합니까?


내 코드는 다음과 같습니다.

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

왜 오류가 Use of unassigned local variable tmpCnt있습니까? 명시 적으로 초기화하지 않았지만 Default Value Table 로 인해 값 유형이 0어쨌든 초기화된다는 것을 알고 있습니다. 참조는 또한 나에게 상기시켜줍니다.

C #에서 초기화되지 않은 변수를 사용하는 것은 허용되지 않습니다.

하지만 기본적으로 이미 수행 된 경우 왜 명시 적으로 수행해야합니까? 내가 할 필요가 없다면 성능이 향상되지 않을까요? 궁금해서 ...


지역 변수는 초기화되지 않습니다. 수동으로 초기화해야합니다.

멤버 는 다음과 같이 초기화됩니다.

public class X
{
    private int _tmpCnt; // This WILL initialize to zero
    ...
}

그러나 지역 변수는 다음이 아닙니다.

public static void SomeMethod()
{
    int tmpCnt;  // This is not initialized and must be assigned before used.

    ...
}

따라서 코드는 다음과 같아야합니다.

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

그래서 길고 짧은 것은 멤버가 초기화되고 로컬은 초기화되지 않는다는 것입니다. 이것이 컴파일러 오류가 발생하는 이유입니다.


기본 할당은 클래스 멤버에 적용되지만 로컬 변수에는 적용되지 않습니다. Eric Lippert 가이 답변 에서 설명했듯이 Microsoft 기본적으로 로컬을 초기화 할 수 있었지만 할당되지 않은 로컬을 사용하는 것은 거의 버그이기 때문에 그렇게하지 않기로 선택했습니다.


다음 범주의 변수는 초기에 할당되지 않은 것으로 분류됩니다 .

  • 처음에 할당되지 않은 구조체 변수의 인스턴스 변수.
  • 구조체 인스턴스 생성자의 this 변수를 포함한 출력 매개 변수.
  • catch 절 또는 foreach 문에서 선언 된 변수를 제외한 지역 변수.

다음 범주의 변수는 초기에 할당 된 것으로 분류 됩니다 .

  • 정적 변수.
  • 클래스 인스턴스의 인스턴스 변수.
  • 처음에 할당 된 구조체 변수의 인스턴스 변수.
  • 배열 요소.
  • 값 매개 변수.
  • 참조 매개 변수.
  • catch 절 또는 foreach 문에서 선언 된 변수.

값 유형에는 기본값이 있고 null 일 수 없지만 사용하려면 명시 적으로 초기화해야합니다. 이 두 규칙을 나란히있는 규칙으로 생각할 수 있습니다. 값 유형은 null이 될 수 없습니다 ==> 컴파일러가이를 보증합니다. 방법을 묻는다면? 받은 오류 메시지가 답입니다. 생성자를 호출하면 기본값으로 초기화됩니다.

int tmpCnt; // not accepted 
int tmpCnt = new Int(); // defualt value applied tmpCnt = 0 

지역 변수에는 기본값이 없습니다.

사용하기 전에 확실히 할당해야합니다. 실제로 기본값이있을 때 합리적인 값을 부여했다고 생각하는 변수를 사용할 가능성을 줄입니다.


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.


The default value table only applies to initializing a variable.

Per the linked page, the following two methods of initialization are equivalent...

int x = 0;
int x = new int();

In your code, you merely defined the variable, but never initialized the object.


See this thread concerning uninitialized bools, but it should answer your question.

Local variables are not initialized unless you call their constructors (new) or assign them a value.


IEnumerable<DateTime?> _getCurrentHolidayList; //this will not initailize

Assign value(_getCurrentHolidayList) inside the loop

foreach (HolidaySummaryList _holidayItem in _holidayDetailsList)
{
                            if (_holidayItem.CountryId == Countryid)
                                _getCurrentHolidayList = _holidayItem.Holiday;                                                   
}

After your are passing the local varibale to another method like below. It throw error(use of unassigned variable). eventhough nullable mentioned in time of decalration.

var cancelRescheduleCondition = GetHolidayDays(_item.ServiceDateFrom, _getCurrentHolidayList);

if you mentioned like below, It will not throw any error.

IEnumerable<DateTime?> _getCurrentHolidayList =null;

참고URL : https://stackoverflow.com/questions/9233000/why-compile-error-use-of-unassigned-local-variable

반응형