alansam

Static variable scopes.

May 3rd, 2021
995
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. #include <stdio.h>
  3.  
  4. //  available to all functions in this compilation unit
  5. static int file_scope = 10;
  6.  
  7. void fn(void);
  8.  
  9. int main() {
  10.   //  available only to main
  11.   static int main_scope = 12;
  12.   for (size_t i_ = 0; i_ < 5; ++i_) {
  13.     printf("file_scope: %3d, main_scope : %3d\n",
  14.            file_scope++, main_scope++);
  15.     fn();
  16.   }
  17.  
  18.   return 0;
  19. }
  20.  
  21. void fn(void) {
  22.   //  available only to this function
  23.   static int fn_scope = 0;
  24.   //  ERROR main_scope not in scope
  25.   // printf("file_scope: %3d, main_scope : %3d\n",
  26.   //         file_scope++, main_scope++);
  27.   printf("file_scope: %3d, fn_scope   : %3d\n",
  28.          file_scope++, fn_scope++);
  29.   fn_scope *= 3;
  30.  
  31.   {
  32.     static int inner_scope = 0;
  33.     printf("file_scope: %3d, inner_scope: %3d\n",
  34.           file_scope++, inner_scope++);
  35.     inner_scope += 5;
  36.   }
  37.   //  ERROR inner_scope not inn scope
  38.   // printf("file_scope: %3d, inner_scope: %3d\n",
  39.   //       file_scope++, inner_scope++);
  40.  
  41.   return;
  42. }
  43.  
RAW Paste Data