6

Possible Duplicate:
How to understand complicated function declarations?

Consider:

char (*(*x())[5])()

How do I dissect this expression?

I think it is a function which return an array of size 5, whose members are pointers to function which receive no input and return a char.

Am I right?

Community
  • 1
  • 1
Jichao
  • 40,341
  • 47
  • 125
  • 198
  • 7
    Check out http://cdecl.org/ for non-trivial declarations. – hmjd Jul 10 '12 at 09:17
  • declare x as function returning pointer to array 5 of pointer to function returning char - http://cdecl.org/ – Artefact2 Jul 10 '12 at 09:17
  • No it's a function that returns a pointer to an array of five pointers to functions taking (C: unspecified parameters | C++: no parameters) and returning a char. Functions are not allowed to return arrays in C or C++. Searching for duplicate... – CB Bailey Jul 10 '12 at 09:18
  • Similar: http://stackoverflow.com/questions/3706704/ – CB Bailey Jul 10 '12 at 09:31
  • @hmjd: actually i know cdecl.org, but i want to know the theory to dissect this kind of expre. – Jichao Jul 10 '12 at 09:38
  • @Jichao - Why? You are never going to need it (except when answering questions here). If you use it in a real program, it is never going to pass a code review. – Bo Persson Jul 10 '12 at 10:21
  • @BoPersson: I saw this expression, so I want to know how, and maybe i'll implement a c or c++ compiler in future, so i am glad to know every details of these two languages. – Jichao Jul 10 '12 at 10:26

2 Answers2

14

Search for "Right-left rule"

In your case, it should be:

         x          : x is a
         x()        : function
        *x()        : returning pointer to
       (*x())[5]    : a 5-element array of 
      *(*x())[5]    : pointer to
     (*(*x())[5])() : function
char (*(*x())[5])() : returning char
Adrian Shum
  • 38,812
  • 10
  • 83
  • 131
  • Not a 5-element array but an array with more than 5 elements. It has at least 6. – user1717828 Sep 28 '18 at 10:17
  • @user1717828 I am curious on what do you mean by that. The declaration is `[5]` which precisely means `array with 5 elements`. Of course you can access beyond the 5th element but that's not what the declaration is telling you. – Adrian Shum Sep 28 '18 at 10:33
  • Well, now I'm just going to leave up my original comment so anyone else prone to fall in the same trap doesn't repeat my mistake. I thought it was accessing the [5] (sixth) member of an array. #noobmistakes – user1717828 Sep 28 '18 at 11:13
12

I have been seeing a lot of weird declarations on Stack Overflow these days.

When I'm lazy, I use cdecl.org:

"declare x as function returning pointer to array 5 of pointer to function returning char"

When not, there is the clockwise spiral rule. <- It is AWESOME

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ArjunShankar
  • 23,020
  • 5
  • 61
  • 83