Funktionspointer ==> keine Typüberprüfung
-
Hallo, warum wird folgendes kompiliert?
#include <stdio.h> void f(int a) { printf("a = %d\n", a); } void a() { printf("hallo\n"); } int main(int argc, char **argv) { void (*p)(); p = f; p(); return 0; }
Ausgabe:
a = -1216691584
Nach meinem Verständnis dürfte die Zuweisung "p =f;" nicht funktionieren...
-
Du vergisst eine oft vergessene Regel der Sprache C: Leere Klammern bedeuten nicht keine Argumente, sondern beliebig viele Argumente. p und f sind daher kompatibel.
Aber selbst wenn du
void (*p)(void);
schreibst, wird dir zumindest der GCC "nur" eine Warnung geben.
-
Der Typ wird korrekt geprüft
void (*p)(); //beliebig viele Parameter void (*p)(void); //keine Parameter
-
§6.3.2.3/8 schrieb:
A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.
If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.Edit: Gilt gar nicht für den Zuweisungsoperator. :p
Das Programm wäre fürvoid (*p)(void); //keine Parameter
tatsächlich falsch:
§6.5.9/2 schrieb:
One of the following shall hold:
— both operands have arithmetic type;
— both operands are pointers to qualified or unqualified versions of compatible types;
— one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void; or
— one operand is a pointer and the other is a null pointer constant.