-1

So this method:

int num (int a = 0)
{
static int b = a;
return b;
}

can be used to set and return a value using num(VALUE), but what I don't understand is why it still returns b when called using num(). Shouldn't it return 0 because of the default parameter? Does it have to do something with b being static? Sorry if this sounds noobish, but I'm new to the language.

ggoooogo
  • 17
  • 1
  • 3
    The first time `num` is called `b` will be set to whatever value `a` has at the time. After that, `b` is never changed; only returned. Therefore, you will continue to get the same value. – Nik Bougalis Apr 08 '15 at 04:18

1 Answers1

5

The static variable is initialized once, the first time that the execution passes through the declaration.

Later calls just use the value.

In C++11 the initialization is thread-safe.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331