Evan Carslake Evan Carslake - 4 years ago 155
C++ Question

C++ Initialize Static Array

I am not sure that this is even possible. From all the examples I have seen, the array is defined within the

{ }
brackets, but in my case it is not much possible.

What I am trying to do is keep this in my drawing function to draw multiple circles that slowly increase in size.

What I am getting by using a debugger is the static array is being reset every time the loop hits.

I have also tried something like
static Rect rc[5] = {}


void fun_called_every_five_seconds() {
static Rect rc[5];

for (int i = 0; i < count; i++) {
int x = rand()%400;
int y = rand()%400;
int r = rand()%200;
rc[i] = Rect (x,y,r,r);
}

rc[0].X += 50;


// I check value of rc[0].X right here
}

Answer Source

the static array is being reset every time the loop hits

well yes, your loop explicitly resets the static array.

The minimal change is to just run the initialization loop once:

void for_fun_called_every_five_seconds() {
    static Rect rc[5];
    static bool init = false;
    if (!init) { // this only happens once
        init = true;
        for (int i = 0; i < count; i++) {
            int x = rand()%400;
            int y = rand()%400;
            int r = rand()%200;
            rc[i] = Rect (x,y,r,r);
        }
    }

    rc[0].X += 50;

    // I check value of rc[0].X right here
}

but this is pretty ugly, and unnecessarily hard to reason about. Prefer something like

class Circles {
    Rect rc[5];
public:
    Circles() {
        for (int i = 0; i < count; i++) {
            int x = rand()%400;
            int y = rand()%400;
            int r = rand()%200;
            rc[i] = Rect (x,y,r,r);
        }
    }
    void for_fun_called_every_five_seconds() {
        // should this also be in a loop,
        // ie. each rc[i] gets increased?
        rc[0].X += 50;
        // I check value of rc[0].X right here
    }
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download