3 ms·
> Pointer casts are ALWAYS bad in C. Nope. There's a reason that void * exists. How would you write a "generic" function like qsort without a pointer cast?
by saagarjha 8y ago
> Pointer casts are ALWAYS bad in C.
Nope. There's a reason that void * exists. How would you write a "generic" function like qsort without a pointer cast?
- caf 8y agoYou don't actually need a cast to write a qsort comparison function, because void * is implicitly converted to and from other pointer types in C. Eg: int compare_xyzzy(const void *a, const void *b) { const struct xyzzy *sa = a; const struct xyzzy *sb = b; return (sa->i > sb->i) - (sa->i < sb->i); } On the other hand, pointer casts are needed if you want to write a function like strchr() (where you can pass a const-qualified pointer, but want to return an unqualified pointer for the case where an unqualified pointer was passed).
- saagarjha 8y agoD'oh! You're right, of course.
- v_lisivka 8y agoIf you want to write "generic" function in C, use #define to generate static function for your specific type. But it much much better to use C++ or Rust instead. Example: https://svnweb.freebsd.org/base/head/sys/sys/tree.h?revision=326256&view=markup https://svnweb.freebsd.org/base/head/sys/sys/tree.h?revision...