Reputation: 1399
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.
Upvotes: 0
Views: 379
Reputation: 58339
Array subscripting a[b]
needs one of a
or b
to be a pointer to a complete object type. A function type is not a complete object type.
6.5.2.1 Array subscripting
Constraints
1 One of the expressions shall have type "pointer to complete object type", the other expression shall have integer type, and the result has type "type".
Note that p + 0
should also be an error for the same reason, and I believe the compiler is failing to produce a required diagnostic message. I asked this about why it's not produced: Should clang and gcc produce a diagnostic message when a program does pointer arithmetic on a function pointer?
6.5.6 Additive operators
Constraints
For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)
Upvotes: 1