当程序对函数指针进行指针算术运算时,clang和gcc是否应生成诊断消息? [英] Should clang and gcc produce a diagnostic message when a program does pointer arithmetic on a function pointer?
问题描述
该程序编译时没有错误,例如使用 clang -Wall -std = c11 ac
和 gcc -Wall -std = c11 ac
。这是clang和gcc中的错误吗?因为没有在指向函数类型的指针上定义算术。
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\n", p);
printf("%p\n", p + 1);
return 0;
}
加法有一个约束,即两个操作数都具有算术类型,或者一个是指向完整对象类型的指针。我相信 p
是指向函数类型的指针,而不是指向任何类型的对象类型的指针。这是C11标准:
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加法运算符
6.5.6 Additive operators
约束
- 此外,两个操作数都应具有算术类型,或者一个操作数应是指向完整对象的
指针对象类型,另一个应具有整数
类型。 (递增等于添加1。)
如果出现以下情况,则要求编译器产生诊断消息任何翻译单元都违反了约束。再次使用C11标准:
Conforming compilers are required to produce a diagnostic message if any translation unit violates a constraint. Again, the C11 standard:
5.1.1.3诊断
5.1.1.3 Diagnostics
- 如果预处理翻译单元或翻译单元
包含违反任何语法规则或约束的条件,则符合标准的实现应至少产生一条诊断消息(以实现定义的
方式标识),甚至如果
行为也明确指定为undefined或
实现定义。在
其他情况下也不必产生诊断消息。
推荐答案
函数指针算法是 gcc扩展
要调用标准合规性,您需要
To invoke standards compliance you need
gcc -std=c11 -pedantic ...
clang -std=c11 -pedantic ...
这篇关于当程序对函数指针进行指针算术运算时,clang和gcc是否应生成诊断消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!