Why do you need to read a declaration of a declaration in C?
In C, for simple cases, it seems like you have to go backwards to read the pointer declarations. For example:
int n;
int *p = &n; // p is a pointer to int
int *const np = &n; // np is a const pointer to int
int *const *npp = &np; //npp is a (non-const) pointer to const pointer to (non-const) int
Although the correct way to parse declaration types is what is called a spiral rule , would it be easier if the parsing rules were different to accommodate reading simple pointers in a different way? For example:
int n;
*int p = &n; // p is a pointer to int
const *int np = &n; // np is a const pointer to int
*const *int npp = &np; // npp is a (non-const) pointer to const pointer to (non-const) int
So my question again is: What was the principle behind this design choice? What prompted the language designers to choose this particular way of declaring types.
source to share
Grammar aside. If I'm not mistaken, the idea is:
int **a;
is as follows. You need to dereference two times to get an int. So const positions also start to make sense.
int * const * a;
This essentially means that you have to dereference once to get a const to int pointer.
You may find it interesting and educational to read about the origin of C. (PDP, B, etc.)
source to share
Why would you read the pointer declaration back in C?
In my opinion, it is difficult to say whether the declaration is really reversed or not.
For example...
I noticed that the way I read the code in my head has changed over the past few years.
Consider the following code:
int *p;
How do you read this code in your head?
-
I read: "p is a pointer to int".
-
Now I read: "pointer int p".
From a commonly used language, my brain changed the way it translated source code into English. This allows me to understand the syntax without feeling backward.
For me, it feels forward, although this is completely subjective and will vary between people.
Also, there are probably many (spoken) languages ββwhere the source code translates well into a spoken sentence without changing the order.
Conclusion
Whether or not a declaration can feel backward may depend on ...
- Your native language.
- How do you translate the code into your own language.
- Size / complexity of the declaration.
source to share