torstai 18. tammikuuta 2018

Dirty C explained

For veterans this is easy, but this is the code I posted last time:

if ( ((unsigned int (*)(void))val)() )
   return;
 
Simply put, this takes a variable 'val', casts it to function pointer (of a function returning unsigned int and taking no parameters, or 'unsigned int fn(void)'), calls it, and if return value is nonzero, returns immediately from this function.

Specifically, cast and calling of function are done in this part:

((unsigned int (*)(void))val)()

Now, this seems very dirty indeed, and function pointers in C often seem to get a lot of bad rap for being dangerous and unsafe. I give you the first part; syntax for function pointers in C is nasty and complex, and can be source of huge compiler angst while you struggle to get the syntax just right. This is why you typically would use a typedef to make the syntax more easier to write - and read.

But dangerous? Not really, not any more than any other feature of C anyway. Aside the syntax already covered, the usage of function pointers is no more complex or dangerous than using any normal pointers. And sometimes they can be extremely useful, for example allowing you to write kind of pseudo-object oriented code with polymorphism and other fun stuff that occasionally can make life so much easier when dealing with complex structures. And in a project you want to hide these complexities behind somewhat simpler API anyway, further hiding the nasty parts from view.

So don't fear function pointers in C, or pointers in general. They just look scary, but they really aren't. As long as you keep the usual security rules in mind.





Ei kommentteja:

Lähetä kommentti