#define IDENTIFIER without a token

前端 未结 4 529
长发绾君心
长发绾君心 2020-12-06 00:05

What does the following statement mean:

#define FAHAD

I am familiar with the statements like:

#define FAHAD 1
相关标签:
4条回答
  • 2020-12-06 00:40

    Defining a constant without a value acts as a flag to the preprocessor, and can be used like so:

    #define MY_FLAG
    #ifdef MY_FLAG
    /* If we defined MY_FLAG, we want this to be compiled */
    #else
    /* We did not define MY_FLAG, we want this to be compiled instead */
    #endif
    
    0 讨论(0)
  • 2020-12-06 00:40

    Any #define results in replacing the original identifier with the replacement tokens. If there are no replacement tokens, the replacement is empty:

    #define DEF_A "some stuff"
    #define DEF_B 42
    #define DEF_C
    printf("%s is %d\n", DEF_A, DEF_B DEF_C);
    

    expands to:

    printf("%s is %d\n", "some stuff", 42 );
    

    I put a space between 42 and ) to indicate the "nothing" that DEF_C expanded-to, but in terms of the language at least, the output of the preprocessor is merely a stream of tokens. (Actual compilers generally let you see the preprocessor output. Whether there will be any white-space here depends on the actual preprocessor. For GNU cpp, there is one.)

    As in the other answers so far, you can use #ifdef to test whether an identifier has been #defined. You can also write:

    #if defined(DEF_C)
    

    for instance. These tests are positive (i.e., the identifier is defined) even if the expansion is empty.

    0 讨论(0)
  • 2020-12-06 00:50
    #define FAHAD
    

    this will act like a compiler flag, under which some code can be done. this will instruct the compiler to compile the code present under this compiler option

    #ifdef FAHAD
    printf();
    #else
    /* NA */
    #endif
    
    0 讨论(0)
  • 2020-12-06 00:52

    it means that FAHAD is defined, you can later check if it's defined or not with:

    #ifdef FAHAD
      //do something
    #else
      //something else
    #endif
    

    Or:

    #ifndef FAHAD //if not defined
    //do something
    #endif
    

    A real life example use is to check if a function or a header is available for your platform, usually a build system will define macros to indicate that some functions or headers exist before actually compiling, for example this checks if signal.h is available:

    #ifdef HAVE_SIGNAL_H
    #   include <signal.h>
    #endif/*HAVE_SIGNAL_H*/
    

    This checks if some function is available

    #ifdef HAVE_SOME_FUNCTION
    //use this function
    #else
    //else use another one
    #endif
    
    0 讨论(0)
提交回复
热议问题