본문 바로가기

C++

[C++] 오버플로우 (Overflow)

반응형

타입의 자료형에 따라 표현할 수 있는 범위를 넘어가면 overflow 또는 underflow 가 발생한다.

 

예를 들어,

'(signed) short (int)' 타입의 자료형은 '-32768 ~ 32767'까지의 정수를 표현할 수 있다.

하지만 이때 short s = 32767; 로 변수를 선언하여 초기화시켜주고 +1을 해주면,

overflow가 발생하여 s = 32768이 아닌 s = -32768 라는 값을 가지게 된다.

 

 


#include <iostream>
#include <limits>

int main(int argc, char **argv){

	using namespace std;
    
	cout << "<short> : " << std::numeric_limits<short>::min() << " ~ " <<
		std::numeric_limits<short>::max() << endl << endl;

	short s = std::numeric_limits<short>::max();
	cout << "s : " << s << endl;
    
	s += 1;
	cout << "s + 1 : " << s << endl;

	return 0;
}

 

 

반응형