Why is this code compiling correctly for the arithmetic on a function pointer?
void my_func(void);
int main(void)
{
void (*p)(void) = &my_func;
// Compile
(void) (*p);
(void) *(p + 0);
// Does not compile
(void) p[0];
return 0;
}
I have always thought that p[0] == *(p + 0)
for complete types. Apparently, p[0] != *(p + 0)
for function pointers.
Note: the C standard does not explicitly forbid function pointer arithmetic. It does not forbid it at all. It says it is undefined. That is a different thing. Many language extensions that are conforming in the terms of the standard have behavior that is undefined by the standard.
Also, if you use a pointer to an incomplete type, then we have:
int main(void)
{
int (*p)[];
// Compile
(void) (*p);
// Does not compile
(void) *(p + 0);
(void) p[0];
return 0;
}
Then effectively p[0] == *(p + 0)
because both triggers the same error for arithmetic on an pointer to an incomplete type. Although here, the C standard does explicitly forbid arithmetic on an pointer to an incomplete type.