Portability and explicit assumptions
State supported targets, check ranges, encode a defined octet format, and separate C17/C23 guarantees from platform conventions.
In this chapter8 sections
Portable C begins by stating what the program needs from its targets. Integer ranges, byte sizes, representations, and library support can differ. We will replace silent assumptions with checks and clearly defined limits.
1. State what must stay the same
Portability can mean preserving accepted values, results, file formats, or interfaces across a selected group of implementations. Those are different commitments. A source program can be valid on two targets while producing different documented size or representation information. Strict portability is a language-level goal, not a claim that every library or operating-system service is available everywhere.
2. Query ranges and C-byte properties
_Static_assert(CHAR_BIT >= 8, "C bytes have at least eight bits");
_Static_assert(sizeof(char) == 1, "sizeof counts C bytes");
long supported = INT_MAX;
sizeof counts C bytes and sizeof(char) is one; CHAR_BIT tells how many bits that byte contains. Standard int provides at least the required minimum range, not universally 32 bits. A 64-bit operating-system label does not determine every type’s size. Use limits and appropriate formats, including %zu for size_t, instead of assuming that long, pointers, and size_t always share a representation.
Exact-width typedefs such as uint32_t are conditional on a matching type being available. Least-width types can express a minimum range without promising an exact storage size. Integer promotions still apply to smaller types, including many typedefs. Before narrowing a value, compare against the destination’s range in a type that can represent the comparison correctly.
unsigned int small = 73U;
unsigned long widened = small;
unsigned int restored = 0;
bool fits = widened <= UINT_MAX;
if (fits) restored = (unsigned int)widened;
3. Define external bytes rather than dumping objects
Little-endian and big-endian are common byte arrangements, not the only layouts C permits. Padding, signed representation, character encodings, and floating-point formats are additional boundaries. Define a file or network format explicitly. Here the format is two eight-bit octets, most significant first; targets without eight-bit C bytes are deliberately rejected by a compile-time requirement.
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
_Static_assert(CHAR_BIT == 8, "This two-octet format requires eight-bit C bytes");
static bool encode_u16(unsigned int value, unsigned char output[2])
{
if (output == NULL || value > 65535U) return false;
output[0] = (unsigned char)(value / 256U);
output[1] = (unsigned char)(value % 256U);
return true;
}
int main(void)
{
unsigned char bytes[2];
bool accepted = encode_u16(0x1234U, bytes);
assert(accepted && bytes[0] == 0x12U && bytes[1] == 0x34U);
unsigned int value = (unsigned int)bytes[0] * 256U + bytes[1];
assert(value == 0x1234U);
return 0;
}
The arithmetic builds each octet rather than reading the host object representation. The caller still supplies two writable elements; the parameter’s [2] spelling does not carry an automatic bounds check. This example is a small format boundary, not a complete serialization framework. Real formats also need lengths, versioning, malformed-record handling, and a policy for extra data.
4. A revision fixes some choices and leaves others open
A shift count must also be nonnegative and less than the width of the promoted left operand. C23 does not remove that bound. Plain char signedness remains a separate implementation choice. Use explicit unsigned operations and proven ranges when designing bit-level formats; even then, account for promotions and widths.
5. Separate language, library, ABI, and operating system
Headers, thread libraries, path syntax, file translation, compiler flags, and binary calling conventions can vary independently. A version macro reports a language revision claim, not every optional library capability. Build and test the supported configuration matrix, document deliberate restrictions, and avoid inferring correctness from a familiar CPU’s tolerance for unaligned access.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 5.2.4.2.1, 6.2.6, 6.3.1.1–6.3.1.3, 6.5.7, 7.20.1. Stable core rules used for the C17 baseline; not the final ISO publication.
- WG14 N3096 — public C23 working draft: 6.2.6.2, 6.3.1.3, 6.5.7. C23 notes are source-reviewed separately from C17 example checks.
The next numeric chapter develops an error budget. External data formats then shows how explicit widths, order, and validation create an agreement between readers and writers.
Before you move on
- Portable design starts by stating which target properties the program needs.
- Language guarantees and implementation-specific choices must be kept distinct.
- Explicit conversions, width checks, and format definitions make assumptions reviewable.
Keep these ideas separate
- Compiles elsewhere / Behaves portably
- Acceptance by another compiler does not alone establish the same intended behavior for all inputs and target assumptions.
Which assumptions would you document before sharing a two-octet numeric format between two machines?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- No. Exact-width typedefs are provided when the implementation has a suitable type.
✓ Correct reasoning. Do not assume an optional exact-width type exists without checking the implementation’s facilities.
- Yes, int is required to be exactly 32 bits.
C17 does not require a universal 32-bit int.
- Yes, including any header creates all integer widths.
A header cannot create an integer representation the implementation does not support.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.
Writing C that behaves identically across platforms requires attention to several dimensions the language deliberately leaves open:
- Type sizes. LP64 on many 64-bit Unix systems uses 64-bit
longand pointers with 32-bitint; LLP64 on 64-bit Windows keepslongat 32 bits. These are platform conventions. Exact-width<stdint.h>types are optional; use them when available, or choose least-width types and check limits when only a minimum range is required. - Endianness. Multi-byte values may use little-endian, big-endian, or other byte arrangements; ISO C does not prescribe one universal byte order. Code that reads raw binary data across different machines — especially over a network — must handle byte order explicitly rather than assuming the local convention.
- Alignment. Respect the C type's alignment requirements. Converting an object pointer to another object-pointer type without suitable alignment can already have undefined behavior; permissive hardware does not make such C code portable. A CPU's handling of an unaligned load is a separate implementation detail.
- Signed-char ambiguity. As noted in Section 14, plain
char's signedness is implementation-defined, which can silently change the result of comparisons or arithmetic performed on character data.
Feature-test macros (such as __STDC_VERSION__) and conditional compilation let a single codebase adapt to these differences at compile time, rather than requiring an entirely separate source tree per platform.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.