Home > front end >  Get value from array in #define
Get value from array in #define

Time:10-05

I have an array defined in a preprocessor statement like that:

#define myArray {0,1,2,3}

When I try to get a value from that array without actually assigning it to a variable first, like so:

myArray[0];

the compiler complains and doesn't let me do that.

This is probably, because this also doesn't work:

{0,1,2,3}[0]

How can I get around this problem? I don't want to use multiple #define statements, and I also don't want to assign the array to a variable in memory first.

Context

I want to implement a patch for an opensource microcontroller project. RAM space is limited, and the whole data flow here is static.

I want to follow the code style in the config file, which uses a lot of array definitions like above.

On the other hand, I don't want to waste RAM space for a useless variable, when it could be done directly.

CodePudding user response:

This can be done with compound literals.

In your case you can do

#define myArray ((int[4]){1,2,3,4})

I would not recommend using compound literals this way. It is unlikely that they are the best solution to your real problem.

CodePudding user response:

#define actually defines a MACRO that the compiler then expands at compilation time to create the executable code that you want.

So you could use:

#define MYARRAY {0,1,2,3}
int testArray[] = MYARRAY;
int element = testArray[0];

but MYARRAY[0] would make no sense to the compiler as there isn't enough information on how the macro should be expanded into executable code, thus it would flag an error.

A word of warning though in the above example the size of testArray isn't determined by the data assigned by the MYARRAY macro, although it will contain the values defined by it, and so the value returned by any sizeof(...) operation may be larger than you expect.

  • Related