Reading declarations with the 'Right-Left' rule
What you'll learn: How to decode even the most confusing C declarations by following a simple visual path starting from the identifier.
The Spiral Logic
In C, declarations don't read simply from left to right like a sentence. Instead, they wrap around the variable name like an onion. If you try to read int *ap[10] as "integer pointer array," you’ll actually get it wrong. To stay sane, we use the Right-Left Rule.
Think of it like a spiral: you start at the variable's name, look to the right for "containers" (like arrays or functions), then look to the left for "qualifiers" (like pointers or data types).
The Three Steps
To decode any declaration, find the identifier (the name) and follow these steps:
- Start at the identifier and say its name.
- Look to the right. If you see
[], say "array of." If you see(), say "function returning." - Look to the left. If you see
*, say "pointer to." If you see a type (likeint), say that type.
If you hit a parenthesis ( ) that groups symbols together, you must finish everything inside that group before moving outside.
The Rule in Action
Let’s look at a declaration that often trips up beginners:
// An array of 10 pointers to integers
int *ap[10];
// A pointer to an array of 10 integers
int (*pa)[10];
For int *ap[10]:
- Start at ap: "ap is..."
- Look right:
[10]means "...an array of 10..." - Look left:
*means "...pointers to..." - Look left:
intmeans "...integers." Result: ap is an array of 10 pointers to integers.
For int (*pa)[10]:
- Start at pa: "pa is..."
- Look right: Hit a
), so we stay inside the group. - Look left:
*means "...a pointer to..." - Move outside the group, look right:
[10]means "...an array of 10..." - Look left:
intmeans "...integers." Result: pa is a pointer to an array of 10 integers.
By following this "Right-Left" zigzag, you can untangle functions that return pointers to arrays, or arrays of function pointers, without ever guessing.
Key takeaway
Always start at the variable name, prioritize the right side (arrays/functions), then move to the left (pointers/types) unless parentheses force you otherwise.