Somehow I’d never encountered this explanation of the mental trick to resolving C type expressions.  It’s blowing my…

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!

http://c-faq.com/decl/spiral.anderson.html

5 thoughts on “Somehow I’d never encountered this explanation of the mental trick to resolving C type expressions.  It’s blowing my…

  1. 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…

    Like

  2. 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

    Like

  3. 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”

    Like

Leave a comment