Course contentsShow
← C
Lesson 498 of 1,2197. PointersFree lesson

The 'Clockwise/Spiral' rule for declarations

The 'Clockwise/Spiral' rule for declarations

What you'll learn: How to accurately read complex pointer declarations by following a simple visual path through the code.

C declarations can look like a bowl of alphabet soup, especially when const and * start piling up. Does int const *ptr mean the pointer is constant, or the integer is constant? To solve this, programmers use a mental trick called the Clockwise/Spiral Rule.

The logic of the spiral

In C, declarations are read starting from the identifier (the name of the variable) and moving outward in a clockwise spiral. As you hit each symbol, you "translate" it into English.

Think of it like peeling an onion from the center. You start at the name, move to the right, then circle back to the left, repeating this circular motion until you've covered every symbol.

The translation key

When you encounter these symbols in your spiral, use these words:

  • *: "pointer to"
  • const: "read-only/constant"
  • int: "integer"

Seeing it in action

Let’s look at a common point of confusion:

// Example A: A pointer to a constant integer
int const * p1;

// Example B: A constant pointer to an integer
int * const p2;

To read Example A:

  1. Start at p1: "p1 is..."
  2. Move right (nothing there but a semicolon).
  3. Circle back left to the *: "...a pointer to..."
  4. Keep circling left to const: "...constant..."
  5. Continue left to int: "...integer." Result: p1 is a pointer to a constant integer. You can change where p1 points, but you can't change the value it points to.

To read Example B:

  1. Start at p2: "p2 is..."
  2. Move right (nothing there).
  3. Circle back left to const: "...a constant..."
  4. Keep circling left to *: "...pointer to..."
  5. Continue left to int: "...integer." Result: p2 is a constant pointer to an integer. You can change the value it points to, but you can never change the address stored in p2.

Why it matters

This rule works for even the most terrifying declarations. By starting at the name and spiraling outward, you ensure you apply qualifiers like const to the correct part of the variable. If you ever get lost, just remember: start at the name and turn right!

Key takeaway

To decode any C declaration, start at the variable name and move in a clockwise spiral to translate symbols into English.