LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

Array Initialization w/ Static Vars - Why does it work?

The following code compiles:

static double a = 1.0;
static double b = 1.1;
static double c = 1.2;
static double d = 1.3;
double *ptr[2][2] = {{&a, &b}, {&c, &d}};

The following code generates an "Initializer must be constant" error:

double a = 1.0;
double b = 1.1;
double c = 1.2;
double d = 1.3;
double *ptr[2][2] = {{&a, &b}, {&c, &d}};

I know that static variables are kept in memory after the function exits, but how does this factor in to them satisfying being "constant" in array initializers?

When I read the error description, I think of const variables (which are const auto, thus not satisfying the error) and hard-coded values. Static variables never even crossed my mind because they are non-constant.

Would anyone like to explain this further?

- Nobody
0 Kudos
Message 1 of 2
(2,865 Views)
Note that the following does not work:

static double a = 1.0;
static double b = 1.1;
static double c = 1.2;
static double d = 1.3;
double ptr[2][2] = {{a, b}, {c, d}}

In your previous example, you were initializing your array with the memory addresses of the static variables.  Since they are static, they are allocated at compile time, and the address of that memory is constant.

Hope this helps.

Mert A.
National Instruments
Message 2 of 2
(2,861 Views)