I am trying to write a special type handling for array data redundancy. The idea is to define and declare an array globally at compile time with fixed size, but the size is different to each declared array. This is the idea:
array[N] = { el1, el2, el3, ..., elN };
At first, I used the following syntax, which works:
#define ARRAY_DEFDEC(name, size, ...) \
int arr_##name[size] = { __VA_ARGS__ }
When I use this macro I get the expected result:
// C code
ARRAY_DEFDEC(array_test, 7, 1, 2, 3, 4, 5, 6, 7);
// Preprocessed
int arr_array_test[7] = { 1, 2, 3, 4, 5, 6, 7 };
Now, for the problem I am having and don't know if it is possible to solve. While doing this, I also need to create a second array for which all the values will be inverted (using ~ operator or alternatively (0 - element + 1)). I have tried ~VA_ARGS, but naturally, it will only change the first element (in the above example with arr_array_test I will get -2, 2, 3, 4, 5, 6, 7).
~
operator to all __VA_ARGS__
?I have a solution which would do the following:
#define ARRAY_DEFDEC(name, size, ...)
int arr_##name[2*size] = { __VA_ARGS__ };
and then it would be used in the following way:
ARRAY_DEFDEC(test, 7, 1, 2, 3, 4, 5, 6, 7, ~1, ~2, ~3, ~4, ~5, ~6, ~7)
This would require quite a lot of logic to be changed and a user needs to know that besides initialising elements, binary inverse needs to be provided, so I do not really prefer to do this.
At this moment in time I am assuming that argument size has the same size as size(__VA_ARGS__
).
The arrays are intended to be used as a global definition (since they need to be accessed by multiple functions).
Note: Since it is an embedded system, external libraries cannot be included. There is not a single standard library on the system (e.g. stdio, stdarg, stdint, etc). This also further limits options. Standard which is used is C99 and compiler is from Green Hill Software.
Is it possible somehow to apply the ~ operator to all VA_ARGS?
No, you have to overload the macro on number of arguments.
Start with a generic FOREACH macro that allows to apply function f on each argument, here's an example for max up to 3 arguments:
#define FOREACH_1(f, x) f(x)
#define FOREACH_2(f, x, ...) f(x) FOREACH_1(f,__VA_ARGS__)
#define FOREACH_3(f, x, ...) f(x) FOREACH_2(f,__VA_ARGS__)
#define FOREACH_N(_3,_2,_1,N,...) FOREACH_##N
#define FOREACH(f, ...) FOREACH_N(__VA_ARGS__,3,2,1)(f, __VA_ARGS__)
Then you would define the array and define a second one with inverted.
// note the comma
#define INVERT(x) ~x,
#define ARRAY_DEFDEC(name, ...) \
int arr_##name[] = { __VA_ARGS__ }; \
int secondarr_##name[] = { FOREACH(INVERT, __VA_ARGS__) };
ARRAY_DEFDEC(name, 1, 2, 3)