… is a matter most c programmers have questioned themselves about once or twice, at least, by now. to do or not to do, that is the question! i have been recently penalized by 2.5 percent in a program, along with a colleague, by not casting the result of the malloc function (a pointer to void, void *) to whatever type we want to use. we have questioned ourselves sometimes before the submission of the work, and so we went and searched for it on google. small forum conversations and programming tutorials suggested that this was no longer necessary, since the void pointer was created to leave the char pointer behind as the arbitrary pointer to objects (data). that was when we decided not to cast.
so today, a few weeks later, the teacher tells us (sorry, we asked!!) we lost some points by not casting the attribution from malloc. so i grabbed the rationale for the ansi c programming language, where two things are clearly stated:
- the pointer to void is a generic pointer, an invention by the ansi comitee to drop the usage of char * as the arbitrary object pointer;
- a pointer to void may be converted to a pointer to any object of any type and vice-versa. even more, the result of the opposite operation compares equal do the original pointer.
a further reading of the text points the reader in the direction that the conversion is done by simple operations, assignment included, not explicit casts.
so, as many people has been preaching in the internet, casting a pointer to void only grants that the user is demanding the compiler to do something it would do anyway. more than that, casting makes you write more code and, when changing code, makes it easier to produce hard to find bugs (imagine you cast, then you change data types, but not the cast!). so, since i’m more or less an advocate of the suckless philosophy, i’m not casting!