Scope of macros in C?

后端 未结 7 1576
不思量自难忘°
不思量自难忘° 2020-12-17 08:03

How these macros are evaluated?

# define i 20
void fun();

int main(){
  printf(\"%d\",i);
  fun();
  printf(\"%d\",i);
  return 0;
}

void fun(){
  #undef          


        
7条回答
  •  佛祖请我去吃肉
    2020-12-17 09:02

    There's no scope involved at all. Macros are handled at the preprocessing stage separately and independently from the compilation stage and have no concept of a C scope. Your examples could just as easily be:

    #define i 20
    
    void fun();
    
    int main()
    {
      printf("%d",i);
      fun();
      printf("%d",i);
      return 0;
    }
    
    void fun()
    {
    }
    
    #undef i
    #define i 30
    

    And:

    #define i 20
    #undef i
    #define i 30
    
    void fun()
    {
    }
    
    int main()
    {
      printf("%d",i);
      fun();
      printf("%d",i);
      return 0;
    }
    

    You can see from those why it behaves the way it does.

提交回复
热议问题