01 Jun

Length vs size for array dimensions

I’m quite particular about how I word the variables that are exposed via my APIs. I always prefix pointers that I write to with out_*, my variables are always in C style this_is_my_variables_name and I try to be as descriptive as possible of what the type is actually going to be used for.

One thing that I tend to pay particular attention to is when I want to pass an array of items into a function. For example;

void foo(int* a, int b);

Is a really awful entry point for an array to an API. First off, there is no correlation in the wording of a and b, even if there was b should be an unsigned type if it is going to point to valid allocated memory. A better approach would be;

void foo(int* a, unsigned a_size);

But there is something I don’t like about this. I don’t like the use of the word ‘size’ here.

Maybe this isn’t the case for all, but for me ‘size’ equates directly to bytes, it is the size of memory allocated to contain a variable or array. If I see an API like the above, I immediately think that the code within that will loop over the array like;

void foo(int* a, unsigned a_size) {
    for (unsigned i = 0; i < (a_size / sizeof(int); i++) {
        ; // do something
    }
}

For me, I would use length in this context – length implies that the memory is allocated such that there is length N int’s in the array. I only use size when I am dealing with void* array pointers – EG. some data that I can make no assumptions what its composition is.

One last quirk with this approach is that some people like to still use size when referring to char* data – EG. an array with a byte-width payload. I would still recommend you use length in this context, because you are still assuming that you will interface with that char* array by simply using the length as a bounding value, like;

void foo(char* a, unsigned a_length {
    for (unsigned i = 0; i < a_length; i++) {
        a[i]; // do something
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *