Quantcast
Channel: Question and Answer » generic-programming
Viewing all articles
Browse latest Browse all 4

Using macros to implement a generic vector (dynamic array) in C. Is this a good idea?

$
0
0

So far I have only done personal projects at home. I hope to get involved in some open source project some time next year. The languages I that have been using the most are C and C++. I have used both languages for over a year and I feel like I have become quite proficient with both of them, but I really don’t know which one I like better.

I personally like C because I think it is simple and elegant. To me C++ seems bloated many unnecessary features that just complicates the design process. Another reason to why I like to use plain C is because it seems to be more popular in the free and open-source software world.

The feature that I miss the most from C++ when I use plain C is probably the std::vector from STL (Standard Template Library).

I still haven’t figured out how I should represent growing arrays in C. Up to this point I duplicated my memory allocation code all over the place in my projects. I do not like code duplication and I know that it is bad practice so this does not seems like a very good solution to me.

I thought about this problem yesterday and came up with the idea to implement a generic vector using preprocessor macros.

It looks like this:

int main()
{
    VECTOR_OF(int) int_vec;
    VECTOR_OF(double) dbl_vec;
    int i;

    VECTOR_INIT(int_vec);
    VECTOR_INIT(dbl_vec);

    for (i = 0; i < 100000000; ++i) {
        VECTOR_PUSH_BACK(int_vec, i);
        VECTOR_PUSH_BACK(dbl_vec, i);
    }

    for (i = 0; i < 100; ++i) {
        printf("int_vec[%d] = %dn", i, VECTOR_AT(int_vec, i));
        printf("dbl_vec[%d] = %fn", i, VECTOR_AT(dbl_vec, i));
    }

    VECTOR_FREE(int_vec);
    VECTOR_FREE(dbl_vec);

    return 0;
}

It uses the same allocation rules as std::vector (the size starts as 1 and then doubles each time that is required).

To my surprise I found out that this code runs more than twice as fast as the same code written using std::vector and generates a smaller executable! (compiled with GCC and G++ using -O3 in both cases).

My question is:

  • Would you recommend using this in a serious project?
  • If not then I would like you to explain why and what a better alternative would be.

Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images