Home > OS >  can I define a array as preprocessor?
can I define a array as preprocessor?

Time:08-12

#define PUMP [0,1]  

when I call a function like this:

for (index = 0;index < 8; index  )
{
get_motor_current(PUMP[index]);
}

The intent is to do get_motor_current([0][index]) and get_motor_current([1][index])

Thank you very much.

CodePudding user response:

You can do it by having the macro expand into a compound literal.

#include <stdio.h>

#define PUMP ((const int[]){0, 1})

int main(void) {
    for (int index = 0;index < 2; index  )
    {
        printf("%d\n", PUMP[index]);
    }
}

CodePudding user response:

Long story short, you can't do what you're trying to do the way you're trying to do it. All the C preprocessor does is perform direct text substitutions. So, after preprocessing, your code snippet would look like:

for (index = 0;index < 8; index  )
{
get_motor_current([0,1][index]);
}

which is not valid C.

Also, square brackets [] are only used for indexing an existing array. If you want to initialize an array with a list of values, you write a list of values enclosed in curly braces {} like so:

int some_array[] = {1, 2, 3, 4};

You don't need to define an array size here (i.e. say some_array[4]) because the compiler just counts the number of items in the list and does that for you.

  • Related