C: Example of unsafe of function pointer compare to delegate of C# -


When I learn a representative of C #, my book said that the function in C is representative with pointer, but more secure . I think after reading the line, I think: Ah, then the compiler will not examine the prototype where the function indicates the indicator. And I'm totally wrong.

  int plus (int a, int b) {back a + b; } Float ADF (Float A, Float B) {return a + b; } Int (* f) (int, int); F = add; // a compilation-error f = add_f; // compile-error   

Therefore, please tell me why, and give me some examples to prove that the C function pointer is unsafe when comparing the representative in C #, please.

Thanks :)

In C ++, the function pointer types are protected < However, in C, however, you have to do something stupid to break them (generally casting, unions, > memcpy or similar, the function types are not nearly strict. Can work well:

  int plus (int a, int b) {back a + b;} int add_f (float a, float b) {a + b return;} int (* F) (); // The empty logic list does not mean zero arguments. For new arguments, add an int (*) (zero) f = and add F = and add_f;   


An example of a stupid stupid For example:

  #include  int add (int a, int b) {back a + b;} int add_f (float a, float b) {A + b return;} consortium {int (* f1) (int, int); int (* f2) (float, float);} fp; int main (zero) {fp.f1 = & add; Std :: cout & lt; << "expected (1):"   

Note that this stupidity is equally possible in C # in Marshall.Copy .

Comments