Should clang and gcc produce a diagnostic message when a program does pointer arithmetic on a function pointer?

萝らか妹 提交于 2020-05-23 21:09:27

问题


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;
}

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

  1. 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

  1. 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.

回答1:


Function pointer arithmetic is a gcc extension also implemented by clang.

To invoke standards compliance you need

gcc -std=c11 -pedantic ...
clang -std=c11 -pedantic ...



回答2:


Add the -Wpointer-arith flag to produce warnings

a.c:8:22: warning: arithmetic on a pointer to the function type 'void (void)' is a GNU extension [-Wpointer-arith]
    printf("%p\n", p + 1);
                   ~ ^

From GNU documentation

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

Clang -Wpointer-arith documentation

warning: arithmetic on a pointer to the function type B is a GNU extension



来源:https://stackoverflow.com/questions/61949561/should-clang-and-gcc-produce-a-diagnostic-message-when-a-program-does-pointer-ar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!