Here is a wacky workaround that I thought of. In order to fulfill this wish though:
I want to use this with everything: functions, int's, floats, strings etc.
I could not escape using pointers
So first, prepare a header file (called "macroArray.h" in this example) like this:
#ifndef MACRO_ARRAY_H
#define MACRO_ARRAY_H
#include <stdio.h>
#include <stdlib.h>
#define ARRINIT(SIZE, INIT_VAL) initArr(SIZE, INIT_VAL)
typedef int Item;
Item **initArr(int aSize, Item *initVal)
{
Item **arr = malloc(aSize * sizeof *arr);
if (arr != NULL)
{
for (int i = 0; i < aSize; i++)
{
*(arr + i) = initVal;
}
}
else
{
fprintf(stderr, "Failed to allocate memory!\n");
exit(1);
}
return arr;
}
#endif /* MACRO_ARRAY_H */
Here is a usage example:
#include "macroArray.h"
int main(void)
{
int size = 10;
int num = 0;
int **arr = ARRINIT(size, &num);
for (int i = 0; i < size; i++)
{
printf("%d ", **(arr + i));
}
printf("\n");
free(arr);
return 0;
}
So...
ARRINIT(10, 0) => {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
Can be done!
What do you think?
Some drawbacks:
- In order to change the type of array, you must change the alias defined by
typedef
in the header file; this is not very "user friendly"
- You must not forget to
free()
the dynamically allocated array
- This probably does not fulfill your wish to use "constant numbers"
- This is like something "that works, but not really"; could be improved