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.
We'll cover the following
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
.
- Start from the identifier
x
. We read it and get "x
is." - We can’t move right.
- Move left to
int
. We read it and get "x
is anint
."
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 (*
) tochar
.ptr2
is a pointer (*
) toint const
. Theptr2
variable points to is constant and can’t be changed. We can changeptr2
and point it somewhere else.ptr3
is a constant pointer (const *
) to anint
. Theptr3
pointer is constant and can be assigned only once. The variable thatptr
points to isn’t constant and can be changed.ptr4
is a constant pointer (const *
) to a constant int (const int
). Theptr4
pointer is constant and can’t be changed to point to a different variable. The variable thatptr4
points to is also constant and can’t be changed.
We also created an animation:
Get hands-on with 1400+ tech skills courses.