Search code examples
c++syntaxgrammar

How to analyze complicated type expressions in C++?


Things seem to become complicated when dealing with compound C++ types.

For example, how to analyze the type of token fp in the codes below?

int *f(int *p, int a)
{
    return p + a;
}

int *(*fp())(int *, int)
{
    return f;
};

Is there a explanation on syntax for the codes?


Solution

  • You start on the name, then proceed outwards, handling stuff on the right first, then stuff on the left, except when parentheses change that:

           fp                 // `fp` is
           fp()               // (look to the right) a function without parameters, returning
          *fp()               // (look to the left) a pointer to
         (*fp())              // (skip parentheses)
         (*fp())(int *, int)  // (look to the right) a function taking `(int *, int)`, returning
        *(*fp())(int *, int)  // (look to the left) a pointer to
    int *(*fp())(int *, int)  // int