Machineboy空

C# - Overflow, Underflow, 오버플로, 언더플로, StackOverflow, checked 본문

언어/C#

C# - Overflow, Underflow, 오버플로, 언더플로, StackOverflow, checked

안녕도라 2025. 2. 25. 13:33

오버플로우(Overflow)란?

변수는 데이터를 담는 그릇과 같다.

그릇에 용량 이상의 물을 담으면 넘치는 것 처럼, 변수에도 데이터 형식의 크기를 넘어선 값을 담으면 넘친다.

  • 각 데이터 형식의 최대값을 넘어가는 데이터를 저장하려고 할 때 발생
uint a = uint.MaxValue;		// 4294967295
a = a + 1;			// 0
  • wrap around under these circumstances. 오버플로 되면 다시 최소값부터 시작되어 할당된다.


 


checked 키워드

  • 정수형의 overflow를 감지하고 예외를 발생시키는 것
int one = 1;
checked
{
    int expr = int.MaxValue + one;   // OverflowException is thrown
}

int expr2 = checked(int.MaxValue + one);     // OverflowException is thrown

스택 오버플로우(Stack Overflow)란?

  • stack memory 영역의 한계를 초과하여 발생하는 오류

대표적 발생 예시 (무한 재귀 호출)

int Sum(int n)
{
	return n + Sum(n-1)
}

언더플로우(Underflow)란?

  • 각 데이터 형식의 최저값보다 작은 데이터를 저장하려고 할 때


오버플로나 언더플로를 적절하게 코드에 이용하는 프로그래머도 있지만, 기본적으롤는 조심해야 하는 현상들이게 때문에 데이터를 다루는 코드를 작성할 때는 다루려는 데이터의 범위와 변수의 형식을 적절하게 맞춰주는 것이 필요하다.

 


예제 

// 각각의 발생 이벤트 종류
// int, long: OverflowException
// float, double: special value of infinity
// decimal: OverflowException
 
 
 // base는 이미 class 처럼 예약어? 지정된 의미와 역할을 가진 것이라, @를 붙여 변수로 사용됨을 표시
 public static string DisplayGDP(float @base, float multiplier)
{
    float result = @base * multiplier;
    if (float.IsInfinity(result))
    {
        return "*** Too Big ***";
    }
    return result.ToString();
}
    public static string DisplayChiefEconomistSalary(decimal salaryBase, decimal multiplier)
    {
        try{
            return checked(salaryBase * multiplier).ToString();
        }
        catch(OverflowException)
        {
            return "*** Much Too Big ***";
        }
    }

 

https://exercism.org/tracks/csharp/exercises/hyperinflation-hits-hyperia/edit

 

Exercism

Learn, practice and get world-class mentoring in over 50 languages. 100% free.

exercism.org