I'm just beginning to wrap my head around function pointers in C. To understand how casting of function pointers works, I wrote the following program. It basically creates a function pointer to a function that takes one parameter, casts it to a function pointer with three parameters, and calls the function, supplying three parameters. I was curious what would happen:
#include <stdio.h>
int square(int val){
return val*val;
}
void printit(void* ptr){
int (*fptr)(int,int,int) = (int (*)(int,int,int)) (ptr);
printf("Call function with parameters 2,4,8.
");
printf("Result: %d
", fptr(2,4,8));
}
int main(void)
{
printit(square);
return 0;
}
This compiles and runs without errors or warnings (gcc -Wall on Linux / x86). The output on my system is:
Call function with parameters 2,4,8.
Result: 4
So apparently the superfluous arguments are simply silently discarded.
Now I'd like to understand what is really happening here.
- As to legality: If I understand the answer to Casting a function pointer to another type correctly, this is simply undefined behaviour. So the fact that this runs and produces a reasonable result is just pure luck, correct? (or niceness on the part of the compiler writers)
- Why will gcc not warn me of this, even with Wall? Is this something the compiler just cannot detect? Why?
I'm coming from Java, where typechecking is a lot stricter, so this behaviour confused me a bit. Maybe I'm experiencing a cultural shock :-).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…