Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, Generic Containers or Safe Containers?

In C++ you can have both generic and type safe containers by using templates. However in C, if you want generic containers, you have to (afaik) use void*, which means you lose type safety. To have type safe containers, you would have to reimplement them for every type of data you want to hold.

Given that C follows a more the-programmer-knows-what-he's-doing philosophy than C++, what would be the more idiomatic thing to do in C: use generic containers with void*, or make custom containers for every type of data?

like image 967
Paul Manta Avatar asked Apr 29 '12 05:04

Paul Manta


People also ask

What are generic containers?

Generic containers are just containers that serve no special purpose. Mostly a style attribute is bounded to a generic container for specifying the rendering or using a CSS rule.

What is a container in C programming?

A container is an object that stores a collection of objects of a specific type. For example, if we need to store a list of names, we can use a vector . C++ STL provides different types of containers based on our requirements.


1 Answers

I'd aim for generic containers:

  1. Once you get used to it, you just think of void * is meaning the type of something when I don't care about it's type. It's like Object in Java -- where, for a long time, generic containers didn't have type safety either.

  2. You only have one place to make improvements.

  3. You don't get the type safety; but with repeated implementations of type safe containers, you run the risk of copy and paste errors. That can lead to errors, too.

like image 170
Edmund Avatar answered Sep 23 '22 11:09

Edmund