Reputation: 2343
I have the following piece of code that I don't fully understand :
void (*foo[ABC]) (int *i) {
[A] = function1,
[B] = function2,
[C] = function3
}
Where A
, B
and C
are integer constants.
1- Is it a valid declaration if ABC
has not been defined before?
2- What is this way of initializing called? ([A] = function1;
)
3- What is the value of foo[D]
? Is it a null pointer?
Upvotes: 2
Views: 440
Reputation:
"I don't think it's C" is not equivalent with "it is not C".
Thanks for the link, @Kninnug -- this is a horrible C99 feature (and a GNU extension to C90), and the code has an error: it is a misspelled initialization of an array of three function pointers. I could imagine the fixed code like this:
#define ABC 3
#define A 0
#define B 1
#define C 2
void function1(int *i)
{
}
void function2(int *i)
{
}
void function3(int *i)
{
}
int main(int argc, char *argv[])
{
void (*foo[ABC]) (int *i) = {
[A] = function1,
[B] = function2,
[C] = function3
};
return 0;
}
Also:
What is the value of
foo[D]
? Is it a null pointer?
Well, what's D
? If D >= ABC
(assuming that they both are non-negative integers), then that element doesn't even exist. If D < ABC
, then it is a NULL
pointer, since aggregate (structure, union and array) initialization implicitly zero-initializes elements that have no corresponding initializer expression in the initializer list.
(More precisely, they are initialized "as if they had static
storage duration", which is initialization to NULL
in the case of pointers.)
Upvotes: 2
Reputation: 8053
ABC
or A
, B
or C
are not defined.D < ABC
, foo[D]
will be 0 (equivalent to a NULL
-pointer), otherwise it will be undefined.EDIT: as the question is now about what it would mean if ABC
Random
and the other indexers are strings the answer is a lot shorter: it won't mean anything, using strings as array indexes is undefined behaviour.
Upvotes: 3