You need to use a #define
for A
, but given that you do that, you can manage using some scheme like this:
#define A 384
#define B_SIZE (A <= 16 ? 3 : A <= 32 ? 4 : A <= 64 ? 5 : A <= 128 ? 6 : \
A <= 256 ? 7 : A <= 512 ? 8 : A <= 1024 ? 9 : -1)
extern int B[B_SIZE];
The use of -1
as the tail value is not accidental; it ensures a compilation error because you can't have arrays with a negative size, so if A
is too big, the code won't compile. You could use the same trick to rule out sizes that are too small, too.
In the code that defines and initializes the array, you use:
int B[B_SIZE] =
{
2, 4,
#if A > 16
8,
#endif
#if A > 32
16,
#endif
#if A > 64
32,
#endif
#if A > 128
64,
#endif
#if A > 256
128,
#endif
#if A > 512
256,
#endif
A/2
};
This isn't elegant, but I'm not sure there's a neater way to do it. This uses B_SIZE
explicitly again to ensure a compilation error again if the value of A
is out of bounds. You could otherwise just leave the B_SIZE
out of the array specification.
You could easily write a shell (Awk, Perl, Python, …) script to generate the code up to a given size.