Course contentsShow
← C
Lesson 926 of 1,21913. Advanced CFree lesson

Reading declarations with the 'Right-Left' rule

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:

  1. Start at the identifier and say its name.
  2. Look to the right. If you see [], say "array of." If you see (), say "function returning."
  3. Look to the left. If you see *, say "pointer to." If you see a type (like int), 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]:

  1. Start at ap: "ap is..."
  2. Look right: [10] means "...an array of 10..."
  3. Look left: * means "...pointers to..."
  4. Look left: int means "...integers." Result: ap is an array of 10 pointers to integers.

For int (*pa)[10]:

  1. Start at pa: "pa is..."
  2. Look right: Hit a ), so we stay inside the group.
  3. Look left: * means "...a pointer to..."
  4. Move outside the group, look right: [10] means "...an array of 10..."
  5. Look left: int means "...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.