Types, declarations, and data interfaces
Read aliases and qualifiers precisely, validate invariants, and introduce opaque interfaces with explicit lifetime contracts.
In this chapter8 sections
A declaration tells us about types and names. A useful data interface also explains valid states, allowed changes, and who manages storage. We will read declarations carefully, then add the promises that their syntax cannot express alone.
1. typedef gives a type another name
struct Point { int x; int y; };
typedef struct Point Point;
Point location = {2, 3};
struct Point copy = location;
The typedef introduces an alias for an existing type, not a distinct incompatible type or an object. Point and struct Point name the same type here. In contrast, separately declared struct Pixel { int x; int y; }; describes another structure type, even though its members look similar. Type identity and similar representation are different facts.
An alias can make a long declaration readable, but it can also hide a pointer. Understand the aliased type before attaching qualifiers or inferring ownership. A name such as Buffer does not itself reveal whether copying it duplicates storage, borrows a view, or transfers responsibility.
2. Qualifiers apply to the type actually named
typedef int *IntPointer;
int value = 4;
const IntPointer fixed = &value;
*fixed = 7;
IntPointer already means pointer to int. Adding const makes this pointer object nonmodifiable after initialization; it does not add const to the pointed-to integer. The integer can be changed through *fixed. This differs from const int *view, which restricts changing an integer through that view.
struct View { int *items; size_t count; };
int numbers[2] = {1, 2};
const struct View view = {numbers, 2};
view.items[0] = 9;
Likewise, a const structure object containing an int * member does not recursively make the target integers const. The member’s pointer value cannot be reassigned through that const structure, but it still provides an int * value used to access its target. Design read-only views with appropriate pointed-to types and document which storage may change. Include <stddef.h> for the fragment’s size_t.
3. Validate relationships at a clear boundary
An invariant is a relationship your operations intend to preserve. Here it is lower <= upper. A constructor-style function is an ordinary C function chosen to establish that relationship, not an automatic language constructor. Its contract should state what happens to the output on failure.
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
struct Range { int lower; int upper; };
static bool make_range(int lower, int upper, struct Range *result)
{
if (result == NULL || lower > upper) return false;
*result = (struct Range){.lower = lower, .upper = upper};
return true;
}
int main(void)
{
struct Range range = {0, 0};
assert(!make_range(5, 1, &range));
assert(range.lower == 0 && range.upper == 0);
assert(make_range(1, 5, &range));
assert(range.lower <= range.upper);
assert(!make_range(1, 5, NULL));
return 0;
}
All checks happen before assignment, so invalid inputs leave the existing output unchanged. A null output pointer is rejected before use. The public structure still lets other code directly write inconsistent members; the function alone cannot prevent that. If every update must go through controlled operations, hide the representation behind an incomplete type.
- Accept inputs
- Check relationships
- Commit valid state
- Report result
4. An incomplete type can define an opaque interface
struct Sensor;
typedef struct Sensor Sensor;
Sensor *sensor_create(int initial_value);
int sensor_read(const Sensor *sensor);
void sensor_destroy(Sensor *sensor);
These are interface declarations, not a complete program. The definitions must be supplied elsewhere. A caller can hold a Sensor * without seeing the structure’s members, while ordinary sizeof(Sensor) or creating a complete Sensor object by value requires the completed type. This is an opaque-type interface, developed further with headers and multiple source files.
The declarations do not yet promise whether create can fail, whether read accepts null, or whether destroy may be called twice. State those rules explicitly. If a function returns ownership, specify the matching release operation. If it returns a borrowed pointer, specify which operation can invalidate it. Const access alone does not communicate either ownership or thread safety.
5. Read the declarator before guessing the interface
int *items[3] declares an array of pointers; int (*items)[3] declares a pointer to an array. int (*operation)(int, int) declares a function pointer, while int *operation(int, int) declares a function returning a pointer. Parentheses and the declarator structure decide the type. A function-pointer typedef can help readability, but calls still need a compatible function type and valid argument contract.
A useful interface description answers five questions together: what counts as valid input, what result is produced, what may change, who manages referenced lifetimes, and how failure is reported. That makes declarations useful documentation rather than a puzzle of stars and brackets.
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.2.5, 6.7.2.3, 6.7.3, 6.7.6, 6.7.8. Stable core rules used for the C17 baseline; this is not the final ISO publication.
Continue with Function pointers and callbacks to turn the declarator into a concrete choice of behavior.
Before you move on
- A typedef gives a type another name and can hide pointer details.
- Qualifiers apply to the actual aliased type, so declarator structure matters.
- Useful data interfaces state valid states, mutation, ownership, lifetime, and failure behavior.
Keep these ideas separate
- Opaque type / Automatic validation
- Hiding representation can control access paths, but its public operations still need valid contracts and implementations.
How can a pointer typedef change the meaning you first expect from a const declaration?
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
- Both a and b.
The star belongs to a’s declarator, not automatically to every name in the declaration.
- Only b.
The star is attached to a’s declarator.
- Only a; b has type int.
✓ Correct reasoning. Read each declarator separately with the shared type specifier.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. Follow the expanded lessons above for the connected explanations.
A few C constructs are notorious for tripping up even experienced programmers, not because the underlying rule is complicated, but because the syntax is easy to misread.
Array of Pointers vs. Pointer to an Array
int *arr[10] and int (*arr)[10] look almost identical but declare very different things:
int *arr[10];— an array of 10 elements, each of which is a pointer toint.int (*arr)[10];— a single pointer to an array of 10ints.
The rule of thumb is that [] binds more tightly than * unless parentheses say otherwise, so reading "from the inside out" (arr is first grouped with whichever operator is closest, respecting any parentheses) resolves the ambiguity every time.
Structures Cannot Be Compared with ==
C does not define == for structure operands; such an expression violates a constraint and requires a diagnostic. Compare the relevant members, for example p1.x == p2.x && p1.y == p2.y && p1.z == p2.z. memcmp compares object representations, not semantic equality: padding bytes may differ, and equal member values can have different representations. A = {0} initializer does not generally guarantee fixed padding bytes, and member stores can change padding even after whole-storage zeroing. Do not use memcmp as a general replacement for member-wise comparison.
Reading Complex Declarations
A declaration like int (*fp)(int, int); reads as "fp is a pointer to a function taking two ints and returning int" — parentheses around *fp are essential, since int *fp(int, int) instead declares a function returning int *. A typedef usually makes this far more readable:
int add(int a, int b); /* definition must be supplied when linking */
typedef int (*BinOp)(int, int);
BinOp fp = add;
Ready for the next idea?
Mark this chapter as read whenever you feel ready.