Somehow I’d never encountered this explanation of the mental trick to resolving C type expressions. It’s blowing my mind right now.
The basic idea is that, due to the way that C’s declaration/expression syntax is put together, you can resolve any unknown element in that expression by resolving elements in a clockwise spiral. Very neat!
This is a great rule. My favorite description of this is in “Deep C Secrets” which is a little more abstract, but I think easier to explain to a newbie.
The interesting thing is the const keyword, If I remember correctly:
const int *x;
and
int const *x;
are the same which… is confusing…
LikeLike
Nice. It does require that you find the middlepoint of the spiral to begin with, but it’s a sound explanation, I have to agree.
LikeLike
Right to left rule. http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations
LikeLike
Matthew Toia Nope.
const int* x; means x is a pointer to an integer or an array of integers and the data pointed to by x cannot be changed. You can point x to somewhere else. In other word, a (mutable) pointer to immutable data.
int const* x; means x is a constant pointer. You can change the data pointed at by x but you cannot point x somewhere else. In other word, an immutable pointer to (mutable) data.
We also have:
const int const*
which is the combination of both: immutable pointer to immutable data
LikeLike
Matthew Toia has it right. Don’t worry too much, Bach Le ; it confuses me too.
These two are equivalent:
int const * x ; // cannot change *x
const int * x ; // cannot change *x
But this one is different:
int * const x ; // cannot change x
Right-to-left (or Spiral) rule works it out, though:
int const * x ; // cannot change *x
“x is a pointer to const int”
const int * x ; // cannot change *x
“x is a pointer to int const”
int * const x ; // cannot change x
“x is a const pointer to int”
const int * const x ; // cannot change x or x*
“x is a const pointer to int const”
int const * const x ; // cannot change x or x*
“x is a const pointer to const int”
const int const * const x ; // sheesh!
“x is a const pointer to const int const”
LikeLike