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

113 views Asked by At

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);
}
2

There are 2 answers

0
Jens On BEST ANSWER

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.

2
Sebastian Redl On

The macro expands to a block. Inside the block is a separate scope, where you can declare variables with the same name as outside. They will shadow the outer variables. Doing this is usually not a good idea.