Search code examples
cloopsstatic

Static variable in a loop vs variable and a loop in a block


In C we can use blocks to restrict the scope of a variable, so is

{
    int var = /* initialization */;

    while(...) {
        // some stuff with var
    }
}

equivalent to

while(...) {
    static int var = /* initialization */;
    // some stuff with var
}

?


Solution

  • No.

    • The initializer of the one with the static keyword must be constant.

      {
         int var = f();
         for ( int j=0; j<2; ++j ) {
            printf( "%d\n", var++ );
         }
      }
      
      printf( "--\n" );
      
      for ( int j=0; j<2; ++j ) {
         static int var = f();
         printf( "%d\n", var++ );
      }
      
      <source>: In function 'main':
      <source>:18:24: error: initializer element is not constant
         18 |       static int var = f();
            |     
      
    • The one with the static keyword exists for the duration of the program, and it will only be initialized once no matter how many times the code is executed. If that code block is in a loop that's executed more than once or in a function that's called more than once, it won't get initialized as often as desired.

      for ( int i=0; i<2; ++i ) {
         int var = 3;
         for ( int j=0; j<2; ++j ) {
            printf( "%d\n", var++ );
         }
      }
      
      printf( "--\n" );
      
      for ( int i=0; i<2; ++i ) {
         for ( int j=0; j<2; ++j ) {
            static int var = 3;
            printf( "%d\n", var++ );
         }
      }
      
      3
      4
      3
      4
      --
      3
      4
      5
      6
      
    • There is only one instance of the variable with the static keyword for the entire program, so it is thus shared by all threads.