Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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

  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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...