More Details on Reading Complex Declarations

Solve a previous exercise using the rules for reading complex declarations. Distinguish between old and new rules in this lesson.

Introduction

We can apply the rule for reading complex declarations to any construct inside the C language.

We can apply it to something as simple as int x.

  1. Start from the identifier x. We read it and get "x is."
  2. We can’t move right.
  3. Move left to int. We read it and get "x is an int."

Particularizing the rule

Remember that when we first learned about pointers, we learned how to read such declarations:

const int* const ptr;

The rule was to always start from the right and go left, reading each keyword. This rule is a particularization of the general one we just discovered.

  • The general rule says to start from the identifier. In the declaration above, the identifier is to the right. Therefore, the particular one says to start from the right.
  • The general rule says to alternate from right to left. However, there is nothing to the right, only to the left. Also, there are no opening braces to stop us from going all the way left. Therefore, the particular rule says to go left all the way.

We’ll provide the same examples that we did back then.

char* ptr1;
const int* ptr2;
int* const ptr3;
const int* const ptr4;

Here’s the answer we found:

  • ptr1 is a pointer (*) to char.
  • ptr2 is a pointer (*) to int const. The ptr2 variable points to is constant and can’t be changed. We can change ptr2 and point it somewhere else.
  • ptr3 is a constant pointer (const *) to an int. The ptr3 pointer is constant and can be assigned only once. The variable that ptr points to isn’t constant and can be changed.
  • ptr4 is a constant pointer (const *) to a constant int (const int). The ptr4 pointer is constant and can’t be changed to point to a different variable. The variable that ptr4 points to is also constant and can’t be changed.

We also created an animation:

Get hands-on with 1400+ tech skills courses.