Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const array initialization from other const arrays

A code snippet like the following:

static const double foo[3] = { 1.0, 2.0, 3.0 };
static const double bar[3] = { foo[0]*foo[0], 3*foo[1], foo[2]+4.0 };

generates a compiler error stating that the initialization values are not constants.

There are some arrays of data (can assume a fixed size) and several other ones, dependent and related to them in fairly simple ways, that would be useful to precompute at compile-time rather than run-time. But since the source data may need to be changed, I would prefer that such changes avoid manually re-computing the dependent arrays.

I suppose one could make some utility that generates a .h file, but at this point I'm curious--is there a way to do something like this (enter the data for a const array only once, but have several other const arrays be dependent on them) in the C preprocessor that's cleaner than (say) defining a preprocessor macro for each and every element of each source array?

P.S. If there's some preprocessor library that could do something like this, I would really appreciate a code example.

like image 436
Stan Liou Avatar asked Aug 31 '25 18:08

Stan Liou


1 Answers

It sounds like your original array is actually a list of special constants, and foo is just a collection of them all.

You can achieve something similar using defines and constructing the arrays from those for use in the program later:

#define SpecialA 1.0
#define SpecialB 2.0
#define SpecialC 3.0

static const double foo[3] = { SpecialA, SpecialB, SpecialC };
static const double bar[3] = { SpecialA*SpecialA, 3*SpecialB, SpecialC+4.0 };
like image 81
Josh B Avatar answered Sep 02 '25 08:09

Josh B