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
  • 4,321
  • 1
  • 25
  • 46
  • 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
  • 30,449
  • 3
  • 47
  • 70
-1

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

Blindy
  • 65,249
  • 10
  • 91
  • 131