[C/C++] Fundamental Type: int
[C/C++] Fundamental Type: int
Abstract
This post provides an in-depth overview of the fundamental C/C++ integer type int, covering its definition, typical size, value range, signed vs. unsigned variants, and practical usage guidelines.
1. Introduction
In C and C++, int is the default integer type used for counting, indexing, and arithmetic. Although the standard guarantees only a minimum range, the actual size and representation of int vary across platforms. Understanding these platform-dependent characteristics is essential for writing portable and correct code.
2. Organization
- Definition & Representation — What the C/C++ standard specifies about
int. - Size & Range — Typical widths, minimum requirements, and value limits.
- Signed vs. Unsigned — Behavior differences and when to use each.
- Usage Guidelines & Pitfalls — Best practices and common mistakes.
3. Sections
3.1. Definition & Representation
- Standard definition:
intis a signed integer type capable of representing at least the range −32,767 to 32,767. - Typical representation: Two’s-complement on almost all modern architectures.
- Underlying bits: Exactly
CHAR_BIT * sizeof(int)bits (whereCHAR_BIT$\ge$ 8).
Click Run ▶
3.2. Size & Range
- Minimum requirements (C99/C++11):
sizeof(int)$\ge$ 2 bytesINT_MIN$\le$ −32767,INT_MAX$\ge$ 32767
- Common implementations:
- 32-bit systems:
sizeof(int) == 4, range $\approx$ $2^{15}$ to $2^{15}-1$ - 64-bit systems: often the same as above for LP64 models
- 32-bit systems:
- Macros: Defined in
<climits>/<limits.h>:INT_MIN,INT_MAX
Click Run ▶
3.3. Signed vs. Unsigned int
- Signed
int: Range includes negative values (INT_MIN…INT_MAX). - Unsigned
int: Range 0 …UINT_MAX(2ⁿ − 1). - Conversions & promotions: Mixed signed/unsigned expressions can lead to unexpected results due to integer promotions.
Click Run ▶
3.4. Usage Guidelines & Pitfalls
- Use
intfor general-purpose loops and counters unless a specific range or performance concern dictates otherwise. - Avoid assumptions about byte size; rely on
sizeof(int)andINT_MAX/UINT_MAX. - Beware of overflow: Signed overflow is undefined; unsigned overflow wraps around.
- Prefer
unsignedonly when non-negative values are guaranteed and wrapping behavior is desirable. - When interfacing with APIs or file formats, match the expected width explicitly (e.g., use
int32_tif 32-bit is required).
1
2
3
4
// Example: prefer unsigned only when safe
for (unsigned int i = 0; i < array_length; i++) {
// ...
}
This focused analysis of the int type lays the groundwork for subsequent posts on other fundamental and fixed-width integer types.
This post is licensed under CC BY 4.0 by the author.