Brydon Gibson
Brydon Gibson

Reputation: 1307

Can I declare an array of constants in the preprocessor?

I have a code segment that basically does the following

int* pins = {2, 3, 5, 7, 10}
for (i = 0; i < NUM_OUTPUTS; ++i{
    output[i].pin = pins[i];
}

(note that the numbers do not follow any discernable pattern, so they must be pre declared)

I'd like this to be done in the preprocessor, as the pins array won't be touched afterwards.I understand I'll have to probably loop through as I'm not experienced enough with preprocessor macros to make a loop and do the assignment (although that would be cool).

I found This but I don't think it's quite what I want.

Can something like this be done? Primarily to free up boot up time/memory usage.

Edit: more information. All I'm trying to do is set up the outputs at compile time - I guess I need to loop through all the outputs in the preprocessor to do so.

Upvotes: 0

Views: 330

Answers (3)

H.S.
H.S.

Reputation: 12679

If the pin array won't be touched afterwards then you can use the compound literal instead of creating pins array.

You can do:

#include <stdio.h>

#define PINS (int[]){2, 3, 5, 7, 10}   //compound literal
#define NUM_OUTPUTS (sizeof(PINS)/(sizeof(PINS[0])))
#define INIT(arr) \
        for (size_t i = 0; i < NUM_OUTPUTS; i++) { \
            arr[i].pin = PINS[i]; \
        }

struct st_pin {
    int pin;
};

int main()
{
    struct st_pin arr[NUM_OUTPUTS];

    INIT(arr);

    //Printing arr
    for (size_t i = 0; i < NUM_OUTPUTS; ++i){
        printf ("arr[%zu].pin: %d\n", i, arr[i].pin);
    }

    return 0;
}

Output:

arr[0].pin: 2
arr[1].pin: 3
arr[2].pin: 5
arr[3].pin: 7
arr[4].pin: 10

Upvotes: 2

David C. Rankin
David C. Rankin

Reputation: 84569

You can take it one step further and define the compound literal so that it is expanded as needed:

#define PINS (int[]){2, 3, 5, 7, 10}
#define NUM_OUTPUTS (int)(sizeof PINS / sizeof PINS[0])
...
    for (int i = 0; i < NUM_OUTPUTS; i++)
        output[i].pin = PINS[i];

(note: the compound literal is supported in C99+, or by compiler extension.)

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222942

for (i = 0; i < NUM_OUTPUTS; ++i)
    output[i].pin = (int []) {2, 3, 5, 7, 10} [i];

Upvotes: 1

Related Questions