Separate area for switch enclosures with static variables with the same name

update: Now I re-tested both the simplified test version and the full code with the restored names, and it works correctly. There was probably some other error somewhere else in my code that was now fixed. Sorry for wasting time and effort; will never publish without a working test in the future. Mea culpa.


I have a C ++ function that I call repeatedly. It has the following snippet

     switch(c)
     {
     case 1:
        {
          static int i = 0;
          if ( ... )  { i = 0; }
          .... 
          break;
        }
     case 2:
        {
          static int i = 0;
          if ( ... )  { i = 0; }
          .... 
          break;
        }
     case 3:
        {
          static int i = 0;
          if ( ... )  { i = 0; }
          .... 
          break;
        }
     }

The idea is that she must remember her condition for each case, and sometimes it must reset.

. (MSV++ 2010 Express Edition), , i , , , ; , , if , i = 0; ... !!! "locals" i ( , if). if .

i (i1, i2, i3), .

- - , ? , { ... } . ? C?

: . .

+3
4

. " " , , .

static .

, :

[C++11: 3.3.5/1]: (6.1) , . .

:

#include <iostream>

void f(const int i)
{
    switch (i) {
        case 3: {
            static int x = 0;
            std::cout << x;
            x = 3;
            std::cout << x << ' ';
            break;
        }

        case 4: {
            static int x = 0;
            std::cout << x;
            x = 4;
            std::cout << x << ' ';
            break;
        }
    }
}

int main()
{
    f(3);
    f(4);
}

// Output: 03 04

, , , x. 03 34.

GCC 4.8; Visual Studio 2012.

+4

. , , ,

{}

.

switch(c)
 {
 case 1:
    {
      static int i = 0;
    }
 case 2:
    {
      static int i = 0;
    }
 case 3:
    {
      static int i = 0; 
    }
 }

, , , , , , ( - , ), . .

+3

, , . . .

, , switch.

#include<stdio.h>
int call_switch(int);
int main()
{
call_switch(2);
call_switch(3);
call_switch(2);
call_switch(3);
return 0;
}

int call_switch(int a){
switch(a)
{ 
   case 2:
   {
     static int i = 5;
     i++;
     printf(" i declared as 5     %d\n",i);
     break;
   }
   case 3:
   {
     static int i = 10;
     i++;
     printf("i declared as 10   %d\n",i);
     break;
   }
}
  // printf("%d",i ); not visible here
  return 0;

}

i declared as  5     6
i declared as 10    11
i declared as  5     7
i declared as 10    12
+1

static scope. .

static , , .

-1

All Articles