This program compiles without errors, for example with clang -Wall -std=c11 a.c
and gcc -Wall -std=c11 a.c
. Is this a bug in clang and gcc? Because arithmetic is not defined on pointers to function types.
#include <stdio.h>
void f(void) {}
int main(void){
void (*p)(void) = f;
printf("%p
", p);
printf("%p
", p + 1);
return 0;
}
There's a constraint on addition that either both operands have arithmetic type, or one is a pointer to a complete object type. I believe p
is a pointer to a function type, not a a pointer to any sort of object type. Here's the C11 standard:
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.)
Conforming compilers are required to produce a diagnostic message if any translation unit violates a constraint. Again, the C11 standard:
5.1.1.3 Diagnostics
- A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined
manner) if a preprocessing translation unit or translation unit
contains a violation of any syntax rule or constraint, even if the
behavior is also explicitly specified as undefined or
implementation-defined. Diagnostic messages need not be produced in
other circumstances.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…