C++ numeric_limits | "타입 한계" 가이드

C++ numeric_limits | "타입 한계" 가이드

이 글의 핵심

std::numeric_limits 는 C++ 표준 라이브러리에서 제공하는 타입의 한계값과 속성을 조회하는 템플릿 클래스입니다. 각 타입의 최대/최소값, 정밀도, 특수 값 등을 컴파일 타임에 확인할 수 있습니다.

numeric_limits란?

std::numeric_limits 는 C++ 표준 라이브러리에서 제공하는 타입의 한계값과 속성을 조회하는 템플릿 클래스입니다. 각 타입의 최대/최소값, 정밀도, 특수 값 등을 컴파일 타임에 확인할 수 있습니다.

#include <limits>
#include <iostream>
using namespace std;

int main() {
    cout << "int 최소: " << numeric_limits<int>::min() << endl;
    cout << "int 최대: " << numeric_limits<int>::max() << endl;
    
    cout << "double 최소: " << numeric_limits<double>::min() << endl;
    cout << "double 최대: " << numeric_limits<double>::max() << endl;
}

왜 필요한가?:

  • 플랫폼 독립성: 플랫폼에 따라 달라지는 타입 한계를 일관되게 조회
  • 타입 안전: 매크로(INT_MAX) 대신 타입 안전한 방법
  • 컴파일 타임: 런타임 오버헤드 없음
  • 표준화: 모든 표준 타입 지원
// ❌ 매크로: 타입 불안전, 헤더 의존
#include <climits>
int max = INT_MAX;

// ✅ numeric_limits: 타입 안전, 표준화
int max = std::numeric_limits<int>::max();

주요 멤버 함수:

멤버 함수설명예시
min()최소값 (정수) 또는 최소 양수 (실수)numeric_limits<int>::min()
max()최대값numeric_limits<int>::max()
lowest()최소값 (실수 포함)numeric_limits<double>::lowest()
infinity()무한대 (실수만)numeric_limits<double>::infinity()
quiet_NaN()NaN (실수만)numeric_limits<double>::quiet_NaN()

주요 멤버 상수:

멤버 상수설명예시
is_signed부호 있는 타입인지numeric_limits<int>::is_signed
is_integer정수 타입인지numeric_limits<int>::is_integer
is_exact정확한 표현인지numeric_limits<int>::is_exact
has_infinity무한대 지원 여부numeric_limits<double>::has_infinity
digits1010진수 정밀도numeric_limits<double>::digits10

정수 타입

// char
cout << "char 최소: " << (int)numeric_limits<char>::min() << endl;
cout << "char 최대: " << (int)numeric_limits<char>::max() << endl;

// short
cout << "short 최소: " << numeric_limits<short>::min() << endl;
cout << "short 최대: " << numeric_limits<short>::max() << endl;

// int
cout << "int 최소: " << numeric_limits<int>::min() << endl;
cout << "int 최대: " << numeric_limits<int>::max() << endl;

// long long
cout << "long long 최소: " << numeric_limits<long long>::min() << endl;
cout << "long long 최대: " << numeric_limits<long long>::max() << endl;

실수 타입

// float
cout << "float 최소: " << numeric_limits<float>::min() << endl;
cout << "float 최대: " << numeric_limits<float>::max() << endl;
cout << "float 정밀도: " << numeric_limits<float>::digits10 << endl;

// double
cout << "double 최소: " << numeric_limits<double>::min() << endl;
cout << "double 최대: " << numeric_limits<double>::max() << endl;
cout << "double 정밀도: " << numeric_limits<double>::digits10 << endl;

특수 값

// 무한대
double inf = numeric_limits<double>::infinity();
cout << inf << endl;  // inf

// NaN
double nan = numeric_limits<double>::quiet_NaN();
cout << nan << endl;  // nan

// 체크
cout << isinf(inf) << endl;  // 1
cout << isnan(nan) << endl;  // 1

실전 예시

예시 1: 안전한 덧셈

bool safeAdd(int a, int b, int& result) {
    if (a > 0 && b > numeric_limits<int>::max() - a) {
        return false;  // 오버플로우
    }
    
    if (a < 0 && b < numeric_limits<int>::min() - a) {
        return false;  // 언더플로우
    }
    
    result = a + b;
    return true;
}

int main() {
    int result;
    
    if (safeAdd(INT_MAX, 1, result)) {
        cout << result << endl;
    } else {
        cout << "오버플로우" << endl;
    }
}

예시 2: 범위 체크

template<typename T>
bool inRange(double value) {
    return value >= numeric_limits<T>::min() &&
           value <= numeric_limits<T>::max();
}

int main() {
    double x = 300.0;
    
    cout << "char 범위: " << inRange<char>(x) << endl;    // 0
    cout << "short 범위: " << inRange<short>(x) << endl;  // 1
    cout << "int 범위: " << inRange<int>(x) << endl;      // 1
}

예시 3: 초기값 설정

template<typename T>
T findMin(const vector<T>& v) {
    if (v.empty()) {
        return numeric_limits<T>::max();
    }
    
    T minVal = numeric_limits<T>::max();
    
    for (T x : v) {
        if (x < minVal) {
            minVal = x;
        }
    }
    
    return minVal;
}

int main() {
    vector<int> v = {5, 2, 8, 1, 9};
    cout << "최소: " << findMin(v) << endl;  // 1
}

예시 4: 타입 정보 출력

template<typename T>
void printTypeInfo() {
    cout << "타입: " << typeid(T).name() << endl;
    cout << "최소: " << numeric_limits<T>::min() << endl;
    cout << "최대: " << numeric_limits<T>::max() << endl;
    cout << "부호: " << (numeric_limits<T>::is_signed ? "있음" : "없음") << endl;
    cout << "정수: " << (numeric_limits<T>::is_integer ? "예" : "아니오") << endl;
    
    if (!numeric_limits<T>::is_integer) {
        cout << "정밀도: " << numeric_limits<T>::digits10 << endl;
        cout << "무한대: " << numeric_limits<T>::has_infinity << endl;
    }
    
    cout << endl;
}

int main() {
    printTypeInfo<int>();
    printTypeInfo<unsigned int>();
    printTypeInfo<float>();
    printTypeInfo<double>();
}

타입 속성

// 부호
numeric_limits<int>::is_signed      // true
numeric_limits<unsigned>::is_signed // false

// 정수
numeric_limits<int>::is_integer     // true
numeric_limits<double>::is_integer  // false

// 정확성
numeric_limits<int>::is_exact       // true
numeric_limits<float>::is_exact     // false

// 무한대
numeric_limits<double>::has_infinity  // true
numeric_limits<int>::has_infinity     // false

자주 발생하는 문제

문제 1: min() 오해

// ❌ 실수 타입 min()은 최소 양수
cout << numeric_limits<double>::min() << endl;  // 2.22507e-308 (0에 가까운 양수)

// ✅ 최소값은 lowest()
cout << numeric_limits<double>::lowest() << endl;  // -1.79769e+308

문제 2: 오버플로우 체크 누락

// ❌ 오버플로우 무시
int x = INT_MAX;
x++;  // UB

// ✅ 체크
if (x < numeric_limits<int>::max()) {
    x++;
}

문제 3: 부호 없는 타입

// ❌ 음수 체크
unsigned int x = 10;
if (x >= 0) {  // 항상 true
    // ...
}

// ✅ 부호 체크
if (numeric_limits<unsigned int>::is_signed) {
    // 실행 안됨
}

실무 패턴

패턴 1: 안전한 타입 변환

template<typename Target, typename Source>
std::optional<Target> safeCast(Source value) {
    if (value < static_cast<Source>(std::numeric_limits<Target>::min()) ||
        value > static_cast<Source>(std::numeric_limits<Target>::max())) {
        return std::nullopt;
    }
    return static_cast<Target>(value);
}

// 사용
auto result = safeCast<int>(300L);
if (result) {
    std::cout << "변환 성공: " << *result << '\n';
} else {
    std::cout << "변환 실패: 범위 초과\n";
}

패턴 2: 센티널 값

template<typename T>
class OptionalValue {
    T value_;
    static constexpr T SENTINEL = std::numeric_limits<T>::max();
    
public:
    OptionalValue() : value_(SENTINEL) {}
    OptionalValue(T value) : value_(value) {}
    
    bool hasValue() const {
        return value_ != SENTINEL;
    }
    
    T value() const {
        if (!hasValue()) {
            throw std::runtime_error("No value");
        }
        return value_;
    }
};

// 사용
OptionalValue<int> opt;
if (opt.hasValue()) {
    std::cout << opt.value() << '\n';
}

패턴 3: 범위 검증

template<typename T>
class BoundedValue {
    T value_;
    
public:
    BoundedValue(T value) {
        if (value < std::numeric_limits<T>::min() ||
            value > std::numeric_limits<T>::max()) {
            throw std::out_of_range("Value out of range");
        }
        value_ = value;
    }
    
    T get() const { return value_; }
};

// 사용
try {
    BoundedValue<int> val(42);
    std::cout << val.get() << '\n';
} catch (const std::out_of_range& e) {
    std::cerr << e.what() << '\n';
}

FAQ

Q1: numeric_limits는 언제 사용하나요?

A:

  • 오버플로우/언더플로우 체크
  • 초기값 설정 (최대/최소값으로 초기화)
  • 타입 정보 확인 (부호, 정수 여부 등)
  • 범위 검증 (타입 변환 전)
// 오버플로우 체크
if (x > std::numeric_limits<int>::max() - y) {
    // 오버플로우 발생
}

// 초기값 설정
int minVal = std::numeric_limits<int>::max();

Q2: min() vs lowest()?

A:

  • 정수: min()lowest()가 같음
  • 실수: min()은 최소 양수 (0에 가까운 값), lowest()는 최소값 (음수)
// 정수
std::cout << std::numeric_limits<int>::min() << '\n';     // -2147483648
std::cout << std::numeric_limits<int>::lowest() << '\n';  // -2147483648

// 실수
std::cout << std::numeric_limits<double>::min() << '\n';     // 2.22507e-308 (최소 양수)
std::cout << std::numeric_limits<double>::lowest() << '\n';  // -1.79769e+308 (최소값)

Q3: 성능 오버헤드는?

A: 없습니다. numeric_limits의 모든 멤버는 컴파일 타임 상수이므로 런타임 오버헤드가 전혀 없습니다.

// 컴파일 타임에 값이 결정됨
constexpr int maxInt = std::numeric_limits<int>::max();

Q4: 커스텀 타입은?

A: numeric_limits를 특수화하여 커스텀 타입을 지원할 수 있습니다.

struct MyInt {
    int value;
};

namespace std {
    template<>
    struct numeric_limits<MyInt> {
        static constexpr bool is_specialized = true;
        static constexpr MyInt min() { return MyInt{-100}; }
        static constexpr MyInt max() { return MyInt{100}; }
    };
}

// 사용
MyInt maxVal = std::numeric_limits<MyInt>::max();

Q5: 플랫폼 독립적인가요?

A: 네, numeric_limits는 플랫폼에 맞게 자동으로 설정됩니다. 32비트와 64비트 시스템에서 다른 값을 반환합니다.

// 32비트: 2147483647
// 64비트: 2147483647 (int는 여전히 32비트)
std::cout << std::numeric_limits<int>::max() << '\n';

// 32비트: 2147483647
// 64비트: 9223372036854775807
std::cout << std::numeric_limits<long>::max() << '\n';

Q6: infinity()와 NaN은 언제 사용하나요?

A: 실수 타입에서 특수 값을 표현할 때 사용합니다.

double inf = std::numeric_limits<double>::infinity();
double nan = std::numeric_limits<double>::quiet_NaN();

// 체크
if (std::isinf(inf)) {
    std::cout << "무한대\n";
}

if (std::isnan(nan)) {
    std::cout << "NaN\n";
}

// 연산
double result = 1.0 / 0.0;  // inf
double invalid = 0.0 / 0.0;  // nan

Q7: numeric_limits 학습 리소스는?

A:

관련 글: size_t & ptrdiff_t, Type Traits.

한 줄 요약: numeric_limits는 타입의 한계값과 속성을 컴파일 타임에 조회하는 표준 라이브러리 템플릿입니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.

  • C++ 템플릿 | “제네릭 프로그래밍” 초보자 가이드
  • C++ Union과 Variant | “타입 안전 공용체” 가이드
  • C++ size_t & ptrdiff_t | “크기 타입” 가이드

관련 글

  • C++ 템플릿 |
  • C++ Union과 Variant |
  • 배열과 리스트 | 코딩 테스트 필수 자료구조 완벽 정리
  • C++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
  • C++ ADL |