Semaphor
Semaphor

Reputation: 1040

C-Preprocessor: Calculate number of elements from an array of structures

Let's say, I have in a C application a structure:

typedef struct {
    int aParameter;
    int anotherParameter;
} Structure_t;

and an array of Structure_t elements:

const Structure_t arrayOfStructres[] = {
    {
        .aParameter = 1,
        .anotherParameter = 2
    },
    {
        .aParameter = 3,
        .anotherParameter = 4
    },
};

The arrayOfStructures is constant, so no changes during runtime. This means, that theoretically the number of elements in the array is known during compilation time. I know I could calculate the number of elements with

sizeof(arrayOfStructures) / sizeof(arrayOfStructes[0]);

during runtime, but how to get the number of elements during compilation time with the preprocessor? As the number of elements may be much more than just the two in the example, counting every element when some are added or removed is not very fast and also error prone.

Upvotes: 1

Views: 1223

Answers (3)

Lundin
Lundin

Reputation: 214300

I know I could calculate the number of elements with sizeof(arrayOfStructures)/sizeof(arrayOfStructes[0]); during runtime

No, that calculation is done at compile-time, so it is what you need.

The only calculation of sizeof that is done in run-time is the special case of VLAs, which doesn't apply here.

Upvotes: 2

Grzegorz Szpetkowski
Grzegorz Szpetkowski

Reputation: 37944

The const qualifier has nothing to do with the number of elements in given array. The arrays in C are of fixed size (well, with notable exception to flexible array member, but it is diffrent thing), with no possibility of extending their elements at runtime.

The sizeof operator will (indirectly) give you the number of elements at compile-time. The only exception is with VLA (variable length) arrays, for which sizeof is calculated are runtime, but even with them, you cannot add more elements after declaration (because of that "variable length" is somewhat unfortunate name).

Upvotes: 2

Ashouri
Ashouri

Reputation: 906

I think you can use _countof Macro which operates at compile time, for more information take a look at here

Upvotes: 0

Related Questions