3 ms·
> C's built-in arrays are super weak, so you need some library to do proper resizable arrays. Since C doesn't have generics, such a library will use void * as t
by flukus 9y ago
> C's built-in arrays are super weak, so you need some library to do proper resizable arrays. Since C doesn't have generics, such a library will use void * as the type for putting values into the array and getting them back out again. You'll be casting at every point of use, and nothing will check to make sure you got the cast right, other than running the code and crashing.
There are other options though like macros and code generation. Code gen in particular can give you more options than generics without sacrificing any type safety.
- comex 9y agoI don't know why macro-based containers aren't more popular. You can have a quite usable interface, and even the implementation isn't that ugly. Example: http://attractivechaos.github.io/klib/#Khash%3A%20generic%20hash%20table http://attractivechaos.github.io/klib/#Khash%3A%20generic%20... This approach isn't just more strongly typed than using void * for everything, it's also typically more efficient. For an array, you can put larger structs directly in the array rather than being forced to use a pointer. For a hash table, the same applies, plus you can avoid expensive indirect calls to compute hashes. (There are alternative non-macro approaches that trade off that overhead for other types of overhead, but you can't do as well as with a specialized container.) I guess you could ask, at that point why not just use C++? And a lot of people do, and the people left writing new C programs are often traditionalists who don't want to switch to new approaches. And to be fair, there are disadvantages to macro-based containers, like increasing build time. But I still think there's room for them to see more adoption.
- mobiletelephone 9y agoI use a code generator. It has a great type system, it's composable, mature and it can even compile pretty fast with the right tooling. It's called C++!
- flukus 9y agoTemplates are good for some things but they only do a fraction of what code generators can do. With code generation you can generate types from database tables, web APIs, etc. You can do things like declaratively declaring database views and generate huge chunks of an application. It can handle all sorts of boiler plate code that you can't do with templates alone.