0

Is a code like this erroneous or ok:

void fun()
{
    if ( CONDITION )
    {
        static MyClass myclass;
        ...
    }
    ...
}

I.e., can static variables be declared inside local scope?

user2052436
  • 3,917
  • 1
  • 21
  • 38
  • Yes, static variables in local scopes are initialised when the scope is first entered, but not destroyed until the program exits. – john Jul 17 '19 at 20:09
  • 1
    Yes. All local variables with static [linkage](https://en.cppreference.com/w/cpp/language/language_linkage) works the same, never mind how many levels down they're nested. – Some programmer dude Jul 17 '19 at 20:13

2 Answers2

0

It's perfectly valid according to the C++ standard. It may be a questionable thing to do / bad practice in some cases, but it's valid and well defined.

Jesper Juhl
  • 28,933
  • 3
  • 44
  • 66
-1

It can, of course. You can easily see that by trying to compile the code.

Blindy
  • 60,429
  • 9
  • 84
  • 123