Can a C macro contain temporary variables?

后端 未结 9 659
忘掉有多难
忘掉有多难 2020-12-16 15:25

I have a function that I need to macro\'ize. The function contains temp variables and I can\'t remember if there are any rules about use of temporary variables in macro subs

9条回答
  •  [愿得一人]
    2020-12-16 15:58

    A not perfect solution: (does not work with recursive macros, for example multiple loops inside each other)

    #define JOIN_(X,Y) X##Y
    #define JOIN(X,Y) JOIN_(X,Y)
    #define TMP JOIN(tmp,__LINE__)
    
    #define switch(x,y) int TMP = x; x=y;y=TMP
    
    int main(){
      int x = 5,y=6;
      switch(x,y);
      switch(x,y);
    }
    

    will become after running the preprocessor:

    int main(){
       int x=5,y=6;
       int tmp9 = x; x=y; y=tmp9;
       int tmp10 = x; x=y; y=tmp10;
    }
    

提交回复
热议问题