C Fixed-Width Integers
In this page:
The Portability Problem
Plain types like int and long don't have a guaranteed size in the C standard -- int is commonly 32 bits today but was 16 bits on older systems, so code that assumes a specific width can silently misbehave when compiled on a different platform.
Example: The Portability Problem
#include <stdio.h>
int main() {
printf("int size here: %zu bytes", sizeof(int));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Signed Fixed-Width Types
<stdint.h> defines int8_t, int16_t, int32_t, and int64_t, each guaranteed to be exactly that many bits wide on every conforming platform, which is exactly what protocol formats, file formats, and hardware registers need.
Example: Signed Fixed-Width Types
#include <stdio.h>
#include <stdint.h>
int main() {
int32_t id = 100000;
printf("%d", id);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Unsigned Fixed-Width Types
The unsigned counterparts uint8_t, uint16_t, uint32_t, and uint64_t follow the same naming pattern and are the standard choice for raw byte buffers, bit flags, and anything that should never represent a negative value.
Example: Unsigned Fixed-Width Types
#include <stdio.h>
#include <stdint.h>
int main() {
uint8_t flags = 255;
printf("%u", flags);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing Fixed-Width Values
Because the underlying type behind int32_t can vary by platform, printf format specifiers like %d aren't strictly portable for it -- <inttypes.h> provides macros like PRId32 and PRIu64 that expand to the correct specifier for each fixed-width type.
Example: Printing Fixed-Width Values
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main() {
int32_t id = 42;
printf("%" PRId32, id);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
When to Use Fixed-Width Types
Reach for fixed-width types when exact size matters -- binary file formats, network packets, embedded registers -- but for everyday counters and loop variables, plain int remains simpler and is often what the platform's CPU handles most efficiently.
Example: When to Use Fixed-Width Types
#include <stdio.h>
#include <stdint.h>
int main() {
int32_t filePacketSize = 1024;
int loopCounter = 0;
printf("%d %d", filePacketSize, loopCounter);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers