Complex C declaration

后端 未结 8 1467
清歌不尽
清歌不尽 2020-11-30 18:47

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

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

How do I read this declaration? Is the

8条回答
  •  眼角桃花
    2020-11-30 19:22

    Standard rule: find the leftmost identifier and work your way out, remembering that [] and () bind before *:

                foo                      -- foo
                foo()                    -- is a function
               *foo()                    -- returning a pointer
              (*foo())[SIZE]             -- to a SIZE-element array
              (*foo())[SIZE][SIZE]       -- of SIZE-element arrays
             *(*foo())[SIZE][SIZE]       -- of pointers
            (*(*foo())[SIZE][SIZE])()    -- to functions
          * (*(*foo())[SIZE][SIZE])()    -- returning pointers
    float * (*(*foo())[SIZE][SIZE])();   -- to float
    

    So imagine you have a bunch of functions returning pointers to float:

    float *quux();
    float *bar();
    float *bletch();
    float *blurga();
    

    Let's say you want to store them in a 2x2 table:

    float *(*tab[SIZE][SIZE])() = {quux, bar, bletch, blurga};
    

    tab is a SIZE x SIZE array of pointers to functions returning pointers to float.

    Now let's decide we want a function to return a pointer to that table:

    float *(*(*foo())[SIZE][SIZE])()
    {
      static float *(*tab[SIZE][SIZE])() = {quux, bar, bletch, blurga};
      return &tab;
    }
    

    Note that you could have several functions that build tables of different functions, or organize the same functions differently:

    float *(*(*qwerbl())[SIZE][SIZE])()
    {
      static float *(*tab[SIZE][SIZE])() = {blurga, bletch, bar, quux};
      return tab;
    }
    

    which is the only reason I can think of to do something like this. You shouldn't see types like this in the wild very often (although they do crop up occasionally, and I've been guilty of writing something similarly heinous).

提交回复
热议问题