Search code examples
c++cfunction-pointersdeclaration

Complex C declaration


I was just going through some code on the Internet and found this:

float * (*(*foo())[SIZE][SIZE])()

How do I read this declaration? Is there a specific set of rules for reading such complex declarations?


Solution

  • I haven't done this in a while!

    Start with foo and go right.

    float * (*(*foo())[SIZE][SIZE])()

    foo is a function with no arguments...

    Can't go right since there's a closing parenthesis. Go left:

    float * (*(* foo())[SIZE][SIZE])()

    foo is a function with no arguments returning a pointer

    Can't go left further, so let's cross the parentheses and go right again

    float * (*(* foo())[SIZE][SIZE])() float * (*(* foo())[SIZE][SIZE])() float * (*(* foo())[SIZE][SIZE])()

    foo is a function with no arguments returning a pointer to an array of SIZE arrays of SIZE ...

    Closing parenthesis reached, left again to reach a pointer symbol:

    float * (*(* foo())[SIZE][SIZE])()

    foo is a function with no arguments returning a pointer to an array of SIZE arrays of SIZE pointers to ...

    Left parenthesis again, so we cross it and go right again:

    float *( *(* foo())[SIZE][SIZE])() float *( *(* foo())[SIZE][SIZE])()

    foo is a function with no arguments returning a pointer to an array of SIZE arrays of SIZE pointers to a function with no arguments...

    And left to the end

    float * ( *(* foo())[SIZE][SIZE])()

    foo is a function with no arguments returning a pointer to an array of SIZE arrays of SIZE pointers to a function with no arguments returning a pointer to float


    And whoever wrote that, please teach him to use typedef:

    // Function that returns a pointer to float
    typedef float* PFloatFunc ();
    
    // Array of pointers to PFloatFunc functions
    typedef PFloatFunc* PFloatFuncArray2D[SIZE][SIZE];
    
    // Function that returns a pointer to a PFloatFuncArray2D
    PFloatFuncArray2D* foo();