본문으로 건너뛰기
Previous
Next
C++ numeric_limits | 'Type Limits' Guide

C++ numeric_limits | 'Type Limits' Guide

C++ numeric_limits | 'Type Limits' Guide

이 글의 핵심

std::numeric_limits is a template class that queries the limit values and properties of types provided by the C++ standard library. You can check the maximum/minimum value, precision, special values, etc. of each type at compile time.

What are numeric_limits?

std::numeric_limits is a template class that queries the limit values ​​and properties of types provided by the C++ standard library. The maximum/minimum value, precision, special values, etc. of each type can be checked at compile time.

#include <limits>
#include <iostream>
// 필요한 모듈 import
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;
}

Why do you need it?:

  • Platform independence: Consistently query type limits that vary depending on the platform
  • Type safety: Type-safe alternative to macro(INT_MAX)
  • Compile time: No runtime overhead
  • Standardization: Supports all standard types```cpp // ❌ 매크로: 타입 불안전, 헤더 의존 #include int max = INT_MAX;

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

**Main member functions**:

| member function | Description | Example |
|----------|------|------|
| `min()` | Minimum value (integer) or minimum positive number (real number) | `numeric_limits<int>::min()` |
| `max()` | maximum value | `numeric_limits<int>::max()` |
| `lowest()` | Minimum value (including real numbers) | `numeric_limits<double>::lowest()` |
| `infinity()` | infinity (real numbers only) | `numeric_limits<double>::infinity()` |
| `quiet_NaN()` | NaN (only real numbers) | `numeric_limits<double>::quiet_NaN()` |

**Major member constants**:

| member constant | Description | Example |
|----------|------|------|
| `is_signed` | Is it a signed type? | `numeric_limits<int>::is_signed` |
| `is_integer` | Is it an integer type? | `numeric_limits<int>::is_integer` |
| `is_exact` | Is this an accurate expression? | `numeric_limits<int>::is_exact` |
| `has_infinity` | Whether to support infinity | `numeric_limits<double>::has_infinity` |
| `digits10` | decimal precision | `numeric_limits<double>::digits10` |

## Integer type

```cpp
// 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;
```## Real number type```cpp
// 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;
```## Special values```cpp
// 무한대
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
```## Practical example

### Example 1: Safe addition

```cpp
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;
    }
}
```### Example 2: Range check

```cpp
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
}
```### Example 3: Initial value settings

```cpp
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
}
```### Example 4: Printing type information

```cpp
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>();
}
```## Type attribute

```cpp
// 부호
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
```## Frequently occurring problems

### Problem 1: min() misunderstanding

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

// ✅ 최소값은 lowest()
cout << numeric_limits<double>::lowest() << endl;  // -1.79769e+308
```### Issue 2: Missing overflow check

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

// ✅ 체크
if (x < numeric_limits<int>::max()) {
    x++;
}
```### Problem 3: Unsigned types

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

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

### Pattern 1: Safe type conversion

```cpp
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";
}
```### Pattern 2: Sentinel value

```cpp
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';
}
```### Pattern 3: Range Validation

```cpp
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: When do you use numeric_limits?

**A**: 
- Overflow/underflow check
- Initial value setting (reset to maximum/minimum values)
- Check type information (sign, integer, etc.)
- Range verification (before type conversion)```cpp
// 오버플로우 체크
if (x > std::numeric_limits<int>::max() - y) {
    // 오버플로우 발생
}

// 초기값 설정
int minVal = std::numeric_limits<int>::max();
```### Q2: min() vs lowest()?

**A**: 
- **integer**: `min()` and `lowest()` are the same
- **Real**: `min()` is the minimum **positive number** (value close to 0), `lowest()` is the minimum value (negative number)```cpp
// 정수
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: What is the performance overhead?

**A**: **None**. All members of `numeric_limits` are **compile-time constants**, so there is no runtime overhead whatsoever.```cpp
// 컴파일 타임에 값이 결정됨
constexpr int maxInt = std::numeric_limits<int>::max();
```### Q4: What is custom type?

**A**: You can support custom types by specializing `numeric_limits`.

```cpp
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: Is it platform independent?

**A**: Yes, `numeric_limits` will be automatically set for your platform. Returns different values ​​on 32-bit and 64-bit systems.

```cpp
// 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: When do you use infinity() and NaN?

**A**: Used to express special values ​​in real numbers.

```cpp
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: What are the numeric_limits learning resources?

**A**: 
- [cppreference.com - std::numeric_limits](https://en.cppreference.com/w/cpp/types/numeric_limits)
- "The C++ Standard Library" (2nd Edition) by Nicolai Josuttis
- "Effective C++" (3rd Edition) by Scott Meyers

**Related posts**: [size_t & ptrdiff_t](/blog/cpp-size-t-ptrdiff-t/), [Type Traits](/blog/cpp-type-traits/).

**One-line summary**: `numeric_limits` is a standard library template that looks up the limits and properties of a type at compile time.

---

## Good article to read together (internal link)

Here's another article related to this topic.

- [C++ template | Beginner's Guide to "Generic Programming"](/blog/cpp-template-basics/)
- [C++ Union and Variant | “Type Safe Unions” Guide](/blog/cpp-union-variant/)
- [C++ size_t & ptrdiff_t | “Size Type” Guide](/blog/cpp-size-t-ptrdiff-t/)

## Practical tips

These are tips that can be applied right away in practice.

### Debugging tips
- If you run into a problem, check the compiler warnings first.
- Reproduce the problem with a simple test case

### Performance Tips
- Don't optimize without profiling
- Set measurable indicators first

### Code review tips
- Check in advance for areas that are frequently pointed out in code reviews.
- Follow your team's coding conventions

---
## Practical checklist

This is what you need to check when applying this concept in practice.

### Before writing code
- [ ] Is this technique the best way to solve the current problem?
- [ ] Can team members understand and maintain this code?
- [ ] Does it meet the performance requirements?

### Writing code
- [ ] Have you resolved all compiler warnings?
- [ ] Have you considered edge cases?
- [ ] Is error handling appropriate?

### When reviewing code
- [ ] Is the intent of the code clear?
- [ ] Are there enough test cases?
- [ ] Is it documented?

Use this checklist to reduce mistakes and improve code quality.

---

## Keywords covered in this article (related search terms)

This article will be helpful if you search for **C++**, **numeric_limits**, **limits**, **limits**, **type**, etc.

---

## Related articles

- [C++ template | ](/blog/cpp-template-basics/)
- [C++ Union and Variant | ](/blog/cpp-union-variant/)
- [Arrays and lists | Complete summary of essential data structures for coding tests](/blog/algorithm-series-01-array-list/)
- [C++ Adapter Pattern Complete Guide | Interface conversion and compatibility](/blog/cpp-adapter-pattern/)
- [C++ ADL | ](/blog/cpp-adl-argument-dependent-lookup/)

---

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

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

- [C++ size_t & ptrdiff_t | '크기 타입' 가이드](/blog/cpp-size-t-ptrdiff-t/)
- [C++ 반복자 | 'Iterator' 완벽 가이드](/blog/cpp-iterator-guide/)
- [C++ 템플릿 | '제네릭 프로그래밍' 초보자 가이드](/blog/cpp-template-basics/)

---

## 이 글에서 다루는 키워드 (관련 검색어)

**C++**, **numeric_limits**, **limits**, **types** 등으로 검색하시면 이 글이 도움이 됩니다.