Reputation: 51
I'm fairly new to C++ and while coming across a reference site, I came across the following code snippet and I've been cracking my head to break it down ever since.
This is what I'm still trying to figure out:
int (*(*callbacks[5])(void))[3]
I've read through part of my C++ help books and (generally) understand the precedence flow. But seeing many operators bunched together has thrown me off and I'm rather confused. I've seen other examples and explanations (here), but the extra [3] subscript on the right just complicates things for me.
I was wondering on how I should approach such kinds of complex code, ie. where do I start, what order should I follow, etc.
Would really appreciate the help! Thanks!!
Upvotes: 2
Views: 1992
Reputation: 3103
Here are the beginnings of a primitive introspective "pretty printer" which lets the C++ compiler itself break things down for you:
#include <iostream>
template <typename T>
struct introspect;
template <>
struct introspect<int> {
static std::ostream& prettyPrint(std::ostream& os) { return os << "int"; }
};
template <typename T>
struct introspect<T*> {
static std::ostream& prettyPrint(std::ostream& os) {
os << "pointer to ";
return introspect<T>::prettyPrint(os);
}
};
template <typename T, std::size_t N>
struct introspect<T[N]> {
static std::ostream& prettyPrint(std::ostream& os) {
os << "array of " << N << " (";
introspect<T>::prettyPrint(os);
return os << ")";
}
};
template <typename Res>
struct introspect<Res(void)> {
static std::ostream& prettyPrint(std::ostream& os ) {
os << "function returning (";
introspect<Res>::prettyPrint(os);
return os << ")";
}
};
int main() {
int (*(*callbacks[5])(void))[3];
introspect<decltype(callbacks)>::prettyPrint(std::cout) << '\n';
return 0;
}
Output:
array of 5 (pointer to function returning (pointer to array of 3 (int)))
Upvotes: 9
Reputation: 30494
That is an array of 5 pointers to functions that take no parameters and return a pointer to an array of 3 ints.
I only figured that out because cdecl.org told me. This is one of those places that a typedef would make things much easier to read:
typedef int (*PointerToArrayOfInts)[3];
typedef PointerToArrayOfInts (*FunctionReturningPointerToArray)(void);
FunctionReturningPointerToArray callbacks[5];
Upvotes: 10
Reputation: 17
int (*(*callbacks[5])(void))[3]
declaring callbacks as array 5 of pointer to function (void) returning pointer to array 3 of int
Upvotes: 1