Search code examples
cmacrosansi-c

Why don't I get a warning when I declare a variable with same name in a macro that already exists in a function?


Playing with a macro and thought about the following scenario. Declaring variable in a macro which already exists in function from which this macro has been called, why compiler doesn't complain. When I declare in a code a variable it give me a warning:

Redefinition of 'temp'

I think that it's intended behavior and have to be documented in the standard (ANSI C), but couldn't find where.

For example this code:

#define TEST() { \
    int temp = 10; \
}

int main() {

    int temp = 999;

    printf("\ntemp: %d", temp);
    TEST();
    printf("\ntemp: %d", temp);
}

Solution

  • Given your code and the macro above, the C preprocessor generates the following:

    int main() {
    
      int temp = 999;
    
      printf("\ntemp: %d", temp);
      { 
        int temp = 10; 
      }
      printf("\ntemp: %d", temp);
    }
    

    This is the code that the C compiler receives.

    The inner { .. } is called a nested scope. In your case this nested inner scope contains a variable temp, of which there is already one in the surrounding outer scope (variable shadowing). And that triggers the warning you're seeing.

    Note: in your particular example, the temp variable is declared in a nested scope, never used, and the scope closes thus removing that variable. It's essentially a NOP.