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.
A type declaration statement specifies the type, length, and attributes of objects and functions. You can assign initial values to objects. A declaration type specification (declaration_type_spec) is used in a nonexecutable statement.
A "declaration" establishes an association between a particular variable, function, or type and its attributes. Overview of Declarations gives the ANSI syntax for the declaration nonterminal. A declaration also specifies where and when an identifier can be accessed (the "linkage" of an identifier).
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With