开发者

C puzzle {MACRO}

开发者 https://www.devze.com 2023-02-09 23:55 出处:网络
I came across the following puzzle somewhere #include <stdio.h> int main() { { /*Fill in something here to make this code compile

I came across the following puzzle somewhere

#include <stdio.h>
int main()
{
    {

        /*Fill in something here to make this code compile  
           ........... 
         */   
        ooOoO+=a;    
    } 
    #undef ooOoO 
    printf("%d",ooOoO开发者_开发技巧); 

    return 0;
}

In short I want to ask how can I use ooOoO in printf after it has been #undef ed?


You need to declare it as a variable:

#define ooOoO int ooOoO = 42; int a = 1; { ooOoO

Macro-replacement is non-recursive; while ooOoO is being replaced, the identifier ooOoO will not be treated as a macro name.


If you are looking for a solution that does not use a macro, then you can simply ignore the #undef directive and never declare ooOoO as a macro. It is permitted in both C and C++ to #undef an identifier that is not defined as a macro.


After reformatting the code (indent) and adding the solution, that's what I receive:

#include <stdio.h>
int main()
{
    {
/*-Insert starts here-*/
    }
    int ooOoO = 0, a=3;
    {
/*-Insert ends here-*/
        ooOoO+=a;      
    }       
    #undef ooOoO 
    printf("%d",ooOoO);       
    return 0;
}

compiles and prints 3


How about this?

#include <stdio.h>
int main(){
    int ooOoO = 0;
    {
        int a = 3;
        ooOoO+=a;
    }
    #undef ooOoO
    printf("%d",ooOoO);

    return 0;
}


#include <stdio.h>
int main(){
{

      /*Fill in something here to make this code compile  

*/
}
int a = 0, ooOoO=0;
#define ooOoO ooOoO
{
/*
      */   
              ooOoO+=a;    
          } 
          #undef ooOoO 
          printf("%d",ooOoO); 

return 0;
}


The #undef undefines the symbol to the preprocessor so that it does not get substituted with something else, but ooOoO still gets to the compiler.

0

精彩评论

暂无评论...
验证码 换一张
取 消