The “right-left” rule is a simple rule to deciphere C declarations.

Cover image by Brett Jordan on Unsplash.

Table of Contents

Reference

Elements

  • x (identifier): x is
  • int (type): integer
  • const: constant
  • *: pointer to
  • []: array of
  • (): funtion returning

Rule

  1. Start from identifier.
  2. Move right until out of symobls or right parenthesis hit.
  3. Move left until out of symbols or left parenthesis hit.
  4. Then repeat step 2 and 3 alternatively until out of all symbols.

P.S. Symbols that have already encountered should be ignored.

Examples

int (*a)[];   // a is a pointer to an array of integers
int *b();     // b is a function returning a pointer to an integer
int (*c[])(); // c is an array of pointers to functions returning an integer
int (*d())[]; // d is a function returning a pointer to an array of integers

Remarks

Illegal combinations

  • [](): cannot have an array of funtions

    You should use an array of pointers to functions.

  • ()(): cannot have a function that returns a function

    You should use first-class functions in C++.

  • ()[]: cannot have a function that returns an array

    You should use a function returing a pointer to dynamically allocated memory.

About typedef

This rule also could be applied to typedef.

For example,

typedef struct {
    ...
} *PType[10];
// typdef (struct { ... }) * PType [10];
// PType is an array (with size is 10) of pointers to struct {...}.