표준 라이브러리 헤더 <limits.h>

표준 라이브러리 헤더 <limits.h>

int는 몇 바이트고 최댓값은 얼마일까요? 이건 표준이 아니라 컴파일하는 환경에 따라 달라져요. 그런데 "2의 보수 32비트" 같은 걸 가정하고 코드를 짜다 보면 다른 환경에서 깨지기 쉬워요. <limits.h>는 타입 지원 라이브러리의 수치 한계 인터페이스로, 언어의 정수 타입들이 가질 수 있는 값의 범위를 알려주는 매크로를 정의해요.

출처: cppreference

본문

정수 타입의 한계(Limits of core language integer types)

매크로 설명
BOOL_WIDTH (C23) bool의 비트 폭
BOOL_MAX (C29) _Bool의 최댓값
CHAR_BIT 바이트(byte)의 비트 폭
MB_LEN_MAX 멀티바이트 문자의 최대 바이트 수
CHAR_WIDTH (C23) char의 비트 폭
CHAR_MIN char의 최솟값
CHAR_MAX char의 최댓값
SCHAR_WIDTH / SHRT_WIDTH / INT_WIDTH / LONG_WIDTH / LLONG_WIDTH (C23) 각각 signed char, short, int, long, long long의 비트 폭
SCHAR_MIN / SHRT_MIN / INT_MIN / LONG_MIN / LLONG_MIN (C99) 각 타입의 최솟값
SCHAR_MAX / SHRT_MAX / INT_MAX / LONG_MAX / LLONG_MAX (C99) 각 타입의 최댓값
UCHAR_WIDTH / USHRT_WIDTH / UINT_WIDTH / ULONG_WIDTH / ULLONG_WIDTH (C23) 부호 없는 각 타입의 비트 폭
UCHAR_MAX / USHRT_MAX / UINT_MAX / ULONG_MAX / ULLONG_MAX (C99) 부호 없는 각 타입의 최댓값
BITINT_MAXWIDTH (C23) 비트 정밀 정수를 선언할 때 _BitInt(N)의 타입 지정자에서 지원되는 최대 폭 N. ULLONG_WIDTH보다 크거나 같음

CHAR_MINCHAR_MAXchar의 부호 여부는 알 수 없지만, 항상 범위가 SCHAR_MINSCHAR_MAX이거나 0UCHAR_MAX 중 하나예요.

시그니처(Synopsis)

#define __STDC_VERSION_LIMITS_H__ 202311L

#define BITINT_MAXWIDTH /* see description */
#define BOOL_MAX /* see description */
#define BOOL_WIDTH /* see description */
#define CHAR_BIT /* see description */
#define CHAR_MAX /* see description */
#define CHAR_MIN /* see description */
#define CHAR_WIDTH /* see description */
#define INT_MAX /* see description */
#define INT_MIN /* see description */
#define INT_WIDTH /* see description */
#define LLONG_MAX /* see description */
#define LLONG_MIN /* see description */
#define LLONG_WIDTH /* see description */
#define LONG_MAX /* see description */
#define LONG_MIN /* see description */
#define LONG_WIDTH /* see description */
#define MB_LEN_MAX /* see description */
#define SCHAR_MAX /* see description */
#define SCHAR_MIN /* see description */
#define SCHAR_WIDTH /* see description */
#define SHRT_MAX /* see description */
#define SHRT_MIN /* see description */
#define SHRT_WIDTH /* see description */
#define UCHAR_MAX /* see description */
#define UCHAR_WIDTH /* see description */
#define UINT_MAX /* see description */
#define UINT_WIDTH /* see description */
#define ULLONG_MAX /* see description */
#define ULLONG_WIDTH /* see description */
#define ULONG_MAX /* see description */
#define ULONG_WIDTH /* see description */
#define USHRT_MAX /* see description */
#define USHRT_WIDTH /* see description */

예를 들어 루프 변수를 int로 선언하고 INT_MAX까지 도는 코드가 있다면, 이 매크로를 기준으로 잡아두면 타입 크기가 다른 환경에서도 안전해요.

더 알아보기

  • 부동소수점 타입의 한계는 <float.h>에서 다뤄요.
  • 정수 타입의 최소 요구 범위도 언어의 산술 타입 문서에서 같이 확인해요.