C, C++ Pointers: Reading & declaring the Pointer declarations the right way

 

The Pointers are always tricky to declare and to read back once declared, a great cause of confusions and errors in understanding the code. So it’s important to declare and read back the Pointers, exactly the right way.


  • Although C and C++ read mostly from top-to-bottom and left-to-right, pointer declarations read, in a sense, backwards.
  static unsigned long int *x[N];        ==>    'array of N elements of pointer to unsigned long int'
  
  declaration specifiers    ==> static unsigned long int
  declarators               ==> *x[N]

C, C++ Compiler Rule:

  • The operators in a declarator group accord-ing to the same precedence as they do when they appear in an expression.
    • you’ll see that [] has higher precedence than *.
    • the function call operator, () have the same precedence as [].
    • As grouping, () have the highest precedence of all.

  • Most of us place storage class specifiers such as static as the first (leftmost) declaration specifier, but it’s just a common convention, not a language requirement.
  *f(int)                       ==>    f is a function returning a pointer
  
  (*f)(int)                     ==>     f is a pointer to a function
  • extern & static are the storage specifiers.
  • inline & virtual are the function specifiers.
  • const & volatile are the type specifiers.

C, C++ Compiler Rule:

  • The order in which the declaration speci-fiers appear in a declaration doesn’t matter.
  typedef void *VP;
  
  const VP vectorTable[]            ==    VP const vectorTable[]
  
  const void *vectorTable[]         ==    void const *vectorTable[]

C, C++ Compiler Rule:

  • The only declaration specifiers that can also appear in declarators are const and volatile.
  void *const vectorTable[]         ==>    Allowed
  
  *const void vectorTable[]        ==>    Error

  • Notice the difference:
  T const *p;                       ==>    pointer to const T
  
  T *const p;                       ==>    const pointer to T

  • Example of Cause of confusions:
  typedef void *VP;

  const VP vectorTable[]            ==>    const void *vectorTable[]    ==>    WRONG interpretation
  
  const VP vectorTable[]            ==>    void *const vectorTable[]    ==>    RIGHT interpretation
  • Correct way of declaration to avoid confusions:
  typedef void *VP;
  
  VP const vectorTable[]            ==>    void *const vectorTable[]    ==>    RIGHT way of decalration and interpretation

  • Another Better way of declaration, to avoid confusions
  • Recognizing the boundary between the last declaration specifier and the declarator is one of the keys to under-standing declarations.
  const int* p;                    ==>     const int *p;

Read full original Blog:

This browser does not support PDFs. Please download the PDF to view it: Download PDF.

</embed>
Reference