This is a situation where C++ really shines: you can use C++ with templates and not only have much cleaner code, but also avoid forcing the compiler to inline every single call to array_push_back. And you don't even need to use anything more than structs and functions, you don't need to go "full OO".
I wish C programmers would be more open to C++ but it seems like they're for the most part pretty closed. That's probably the C++ community's fault, but I'm not sure how to make amends.
It is not an all or nothing approach. It's fine to write code that looks and feels mostly like C, but still takes advantage of a few nice C++ features.
One of my largest gripes making the switch, is the OO paradigm. I get it, I understand it, and I really want to love it. But the theory of it vs. the implementations that I've seen, ugh. And the number of ways you can initialize variables etc... just makes no sense to me. It's like they just keep adding new ways to do things, for no other reason than because they can. What's wrong with only have one way to do simple things like that?
I don't know, maybe it's just me but I strive to keep my code as simple, concise as I possibly can. I have enough complexity to deal with solving problems than having to wrestle with my language on top of it. Just to note, I'm strictly talking about having to use other people's code merged with my own. If it was solely me writing, I'd just use C++ for some of the nice things built in and toss classes and all that into the fire. YMMV.
If one would include vector, string, array, smart pointers and maybe simple template code in C+ it would already have a big safety advantage over plain C.
A good example is how Turbo Vision, Object Windows Library, Visual Components Library, Qt look like and the concessions Microsoft had to make to Afx so that it got rebranded into MFC and appealed to the Windows C developers.
By the way, why is this C implementation something that requires C99 or C11 features? It looked just like standard old-fashioned ANSI C to me.
Actually, you really, really, really want to inline every call to push_back for std::vector. Here is a relevant presentation by Chandler Carruth https://www.youtube.com/watch?v=s4wnuiCwTGU . But, hey, you don't want to make the compiler work for you :).
Writing C takes more effort in some cases, so it's a trade-off.
Basically what go and rust have achieved, except you keep most of the C/C++ syntax "taste", and you remove too high level stuff like templates and inheritance. Honestly I don't think templates are so useful, since most programmers already re-use STL containers, which are templates, but nobody really write relevant template classes.
> That's probably the C++ community's fault
The problem with C++ is backward compatibility with C and big corporations trying to not break their codebase. It makes it very hard to make the language evolve. For example D is a very good language, but it can't gain momentum as long as it doesn't have a real way to gain presence. We just have to wait that corporation clean their codebase to make room for C++ compilers to adapt, and then things should improve.
I agree but passing in the size is really not much of a deterrent.
And I had that same idea, let's use macro to fake generic programming. But while I admire the trickery some people pull off using the C preprocessor, I admire them from afar. My coworkers would not have let me get away with that, anyway.
I am not a C++ programmer, but templates are immensely powerful, and after learning about them (a little, at least), I found statically typed languages without some form of type-generic programming to be very bothersome.
Looking at C++ as "C with Templates" instead of "C with Classes" gives a very different picture (plus, Classes and such are still around in case they are needed, anyway). Every other year or so, I try to get my C++ up to usable standards, but I do not need it for work (except for that one time about three years ago), so I eventually lose interest. Maybe approaching C++ as "C with Templates" is a more promising route.
Genius. I'm doing this from now on.
https://github.com/kev009/cii/blob/master/src/array.c - this leaves resizing on the caller, but that could be retrofitted in. Most importantly is how the book explains everything.
When macros start being used for metaprogramming in C, it's time to reconsider using C++.
[1] https://github.com/faragon/libsrt
[2] https://faragon.github.io/svector.h.html
[3] https://github.com/faragon/libsrt/blob/master/doc/benchmarks...
"That will solve my problem elegantly", I thought, but unfortunately, the compiler we used only understood C89, so my hands were tied.
It is an excellent alternative for numerics when you usually work with simple types like int and double.
I eventually moved to a solution where I prepended the capacity and size to the block returned to the caller and then wrote helper functions that accessed/modified these values. This way the caller can access values in the returned array just as they would one returned from malloc.
The code (note, the `vec` type is just a typedef'd `void*`): https://github.com/crossroads1112/marcel/blob/master/src/ds/...
The API is very easy, and it's really fast.
vector<int> vec(5);
vec.push_back(11);
vec.push_back(12);
Now you have in vec: 0, 0, 0, 0, 0, 11, 12
But your suggestion is better from an API point of view.how about #define PUSH_BACK(a,x,t) push_back(a,&x,sizeof(t))
No multi-evaluation problems or other madness.
Edit: Actually that won't work for expressions. So
#define PUSH_BACK(a,x,t) do { t tmp = x; push_back(a,&tmp,sizeof t) } while(0)
slightly better.
You can do better than this!
What is an array? It's 3 variables: base, length and capacity. So why not decide that an array is just that. 3 variables of the right size and type.
#define ARRAY(T,S) T S;size_t S##_length;size_t S##_capacity
Then you can make one like this: ARRAY(int,xs);
You'll also need to initialise and these destroy array "objects". #define ARRAY_INIT(S) \
do { \
S=NULL; \
(S##_length)=0; \
(S##_capacity)=0; \
} while(0)
#define ARRAY_DESTROY(S) \
do { \
Array_Free(S); \
ARRAY_INIT(S); \
} while(0)
Add you'll probably want to add an item to an array too. #define ARRAY_ADD(S,X) \
do { \
if((S##_length)>=(S##_capacity)) { \
S=Array_Grow(S, \
sizeof *S, \
&(S##_length), \
&(S##_capacity)); \
S[S##_length++]=(X); \
} while(0)
So you might use them like this: ARRAY(int,xs);
ARRAY_INIT(xs);
for(int i=0;i<100;++i)
ARRAY_ADD(xs,i);
ARRAY_DESTROY(xs);
Array_Free is very simple, and Array_Grow is barely more complicated (however I wrote it off the cuff, so of course it could still be wrong). Both of these mainly exist just to keep stdlib.h out of the header. void Array_Free(void *p) {
free(p);
}
void *Array_Grow(void *base,size_t stride,size_t *length,size_t *capacity) {
*capacity+=*capacity/2;
*capacity=MAX(*capacity,MAX(MIN_CAPACITY,*length));
return realloc(base,*capacity*stride);
}
Array accesses and iteration and the like are just done in the traditional way: for(size_t i=0;i<xs_length;++i) {
printf("%d\n",xs[i]);
}
Even performs nicely with -O0.For a full implementation you'll probably also need a way of generating a static array. (I mainly found myself needing this for test code, which uses globals for convenience; most arrays I create normally are locals, or parts of structs.)
You'll also need a parameters list for use in a function declaration or definition, and a macro that expands to all 3 variables.
#define ARRAY_PARAMS(T,S) T *S,size_t S##_length,size_t S##_capacity
#define ARRAY_ARG(S) S,S##_length,S##_capacity
Like then you might have a function that takes a pointer to an "array": void FunctionThatTakesAnArray(ARRAY_PARAMS(T,*p));
And you call it like this: ARRAY(T,myarray);
FunctionThatTakesAnArray(ARRAY_ARG(&myarray));
(I found this cropped up often enough that I needed the macro, but it was less common than I thought.)There's more you can do, but the above is the long and the short of it.
This might all look terrible - or perhaps it sort of looks OK, but you're just not sure that it would actually work - but I've used this in a prototype project and thought it worked out well. (I've been using C for 20+ years, so hopefully even if I've got no taste, I've at least got a rough feel for what works out OK and what's going to end up a disaster.)
I think C++ solves this in a neater way (not saying it's good, just better) with templates, the iterator idea, and the algorithms library because you only write things once and the code is only generated for each type (not each use of the function like it would with macros).
struct vec_header_t {
size_t length;
size_t capacity;
};
static inline struct vec_header_t *vec_to_header(void *vec)
{
return ((struct vec_header_t *)vec) - 1;
}
#define _vec_length(vec) (vec_to_header(vec)->length)
static inline void vec_free(void *vec)
{
if (vec)
free(vec_to_header(vec));
}
#define vec_foreach(vec, iter) \
for ((iter) = (vec); (iter) < ((vec) + vec_length(vec)); ++(iter))
It's slightly more cognitive overhead when, for example, debugging, but the vast improvement in usability (no special macros for normal/static declaration, trivial passing to functions, etc) is worth it IMHO.I don't understand why you don't wrap this in a struct, something like (not tested):
#define MAKE_ARRAY_T(T) typedef struct array_##T { T data; size_t length; size_t capacity; } array_##T;
(This could be generalized for types that don't paste cleanly with ##, requiring the user to specify an extra type name.)This would buy you several advantages:
- shallow copies of arrays using =
- easier parameter passing
- easier declarations due to real type names: array_int my_integer_array;
data_type *pp = arr->data;\
this is expanded to something like (when data_type is double): double *pp = arr->data;
You can get rid of the third parameter. Just store the size of the data type in the container struct and use memcpy. Something like this (probably slower than the original): char *pp = arr->data;\
memcpy(pp + (size - 1) * arr->size_of_data, &(x), arr->size_of_data);\Array a; a.add(&a, item).