How can I make sense of this C type declaration?

2019-05-01 15:57发布

问题:

double (*bar(int, double(*)(double,double[])))(double);

While reviewing a lecture slide, I found an exercise left to the student:

In plain English, what is the type of bar in this C declaration?

Please help walk me through this. I don't even know where to begin, except that something is ultimately returning a double.

回答1:

This answer is brought to you by the ability to use the Spiral Rule. Being able to understand a complex expression by starting at the unknown element and reading around it (resolving things in the parenthesis first). A very useful skill when reading code.

        bar                                            - bar
        bar()                                          - is a function
        bar(int, )                                     - which takes an int...
        bar(int, (*)())                                - and a function pointer
        bar(int, double(*)())                          - which returns a double
        bar(int, double(*)(double, ))                  - and takes a double...
        bar(int, double(*)(double, double[]))          - and an array of doubles
      (*bar(int, double(*)(double, double[])))         - and returns a pointer
      (*bar(int, double(*)(double, double[])))()       - to a function
      (*bar(int, double(*)(double, double[])))(double) - taking a double
double(*bar(int, double(*)(double, double[])))(double) - which returns a double

That was the hard way... There are of course sites that make this easier, the cdecl site for example; but it's good to be able to read code even when you can't get to the internet.



回答2:

If you're not sure you can always use the cdecl utility described in K&R like so:

$ cdecl
Type `help' or `?' for help
cdecl> explain double (*bar(int, double(*)(double,double[])))(double);
declare bar as function 
(int, pointer to function (double, array of double) returning double)
returning pointer to function (double) returning double

So bar is a function that takes an int and a pointer to a function that takes a double and double[] and returns a double:

double(*)(double,double[]))

And bar returns a pointer to another function that takes a double and returns a double

double(*)(double)


标签: c declaration