Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading