11

A static variable inside a function is only allocated once during the lifetime of the program.

So if I have a function like:

void f(int n) {

  static int *a = new int[n];

}

and I first call

f(1)

and then

f(3)

how big will the array a be after the second call?

user695652
  • 4,105
  • 7
  • 40
  • 58

4 Answers4

8

static variables local a function are initialized the first time control passes through them. The relevant section in the standard is 6.7 [stmt.dcl]. That is, the array will acquire size 1 and keep this size unless you change its size explicitly.

What's nice in C++ 2011 is that initializing the static variable is also thread-safe: if another thread reaches the instance while the variable is being initialize, the second thread is blocked until initialization is complete.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
6

static local variables will be initialized when the control flow reaches the declaration for the first time. In this case, since the first time you used 1 as the n parameter, you'll be allocating size for one int.

Doing this kind of stuff is a bad idea. You should just use a local, non-static, std::vector or some other higher level container.

mfontanini
  • 21,410
  • 4
  • 65
  • 73
  • 1
    Actually, this is not correct. The control needs to pass through them, i.e., it isn't necessarily the first call. Consider `void f(bool flag) { if (flag) { static int* a = new int[3]; } }` and the calls `f(false); f(true);`: the first call will not initialize the array but the second one will. – Dietmar Kühl Nov 20 '12 at 19:40
3

Initialization of static variables within a function only occurs during the first evaluation of the static statement within function. The first time when f is invoked with f(1), the initialization for a will occur, and it will point to an array of a single int. When f(3) is called, a has already been initialized, so the right hand side of:

static int *a = new int[n];

will not be evaluated again, and a will continue to point to the originally allocated array of size 1.

NickR
  • 51
  • 2
0

The array will be size 1, since the initialization of the variable 'a' is only done once, the first time the function 'f' is called.

Liam
  • 1,472
  • 1
  • 10
  • 14