Complex C declaration

后端 未结 8 1466
清歌不尽
清歌不尽 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:17

    This document gaves me the best clue about how to easily ready any C declaration :

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

    There are three simple steps to follow:

    • Starting with the unknown element, move in a spiral/clockwise direction; when ecountering the following elements replace them with the corresponding english statements:

      • [X] or [] => Array X size of ... or Array undefined size of ...

      • (type1, type2) => function passing type1 and type2 returning ...

      • * => pointer(s) to ...

    • Keep doing this in a spiral/clockwise direction until all tokens have been covered.

    • Always resolve anything in parenthesis first!

    Example :

                 +-------+
                 | +-+   |
                 | ^ |   |
            char *str[10];
             ^   ^   |   |
             |   +---+   |
             +-----------+
    
    Question we ask ourselves: What is str?
    
    ``str is an...
    
    - We move in a spiral clockwise direction starting with `str' and the first character we see is a `[' so, that means we have an array, so...
      ``str is an array 10 of...
    
    - Continue in a spiral clockwise direction, and the next thing we encounter is the `*' so, that means we have pointers, so...
      ``str is an array 10 of pointers to...
    
    - Continue in a spiral direction and we see the end of the line (the `;'), so keep going and we get to the type `char', so...
    ``str is an array 10 of pointers to char''
    
    We have now ``visited'' every token; therefore we are done!
    

提交回复
热议问题