When I learn delegate of C#, my book said that delegate same with function pointer in C, but more safer. After I read that line, I think : Ah, so C Compiler will not check prototype where the function pointer points to. And I’m totally wrong.
int add(int a, int b){ return a + b; }
float add_f(float a, float b){ return a + b; }
int (*f)(int,int);
f = add; // no compile-error
f = add_f; //compile-error
So, Please tell me why, and give me some examples to prove that C function pointer is unsafe when compare to delegate in C#, please.
Thanks 🙂
In C++, function pointers are type-safe. You have to do something spectacularly stupid to break them (generally involving casting, unions,
memcpy, or similar; it can’t happen by accident).In C, though, function types aren’t nearly as strict. You can do things like this:
http://ideone.com/Y6mCc
I was asked for an example of spectacularly stupid. Here goes:
Note that this foolishness is equally possible in C# with
Marshal.Copy.