Search code examples
c++cscopestaticshadowing

Defining a variable and its static equivalent in the same function


I don't understand how the following code works:

#include "stdio.h"

int main(void) {
  int i = 3;
  while(i--) {
    static int i = 100;
    i--,
    printf("%d\n", i);
  }
  return 0;
}

The code compiled with either Clang or GCC prints the following output:

99
98
97

Can someone explain to me what happens here? It looks like two operations are achieved in a single instruction and more than once. Is it undefined behavior? I observe the same behavior in C++.


Solution

  • This is not undefined behavior.

    #include "stdio.h"
    
    int main(void) {
      int i = 3; //first i
      while(i--) {
        static int i = 100; //second i
        i--,
        printf("%d\n", i);
      }
      return 0;
    }
    

    In while loop body most local i (second i) is preferred. While checking condition in while loop it doesn't know what is there in body. So it has no problem choosing first i.