How to define macro function which support no input parameter and support also input parametr in the same time

前端 未结 4 1727
不知归路
不知归路 2021-01-15 22:12

I want to define a macro function which support at the same time:

1) No input parameter

2) Input parameters

some thing like that:

#de         


        
相关标签:
4条回答
  • 2021-01-15 22:28

    You can use sizeof for this purpose.

    Consider something like this:

    #define MACRO_TEST(X) { \
      int args[] = {X}; \
      printf("this is a test\n");\
      if(sizeof(args) > 0) \
        printf("%d\n",*args); \
    }
    
    0 讨论(0)
  • 2021-01-15 22:32

    Not exactly that but ...

    #include <stdio.h>
    
    #define MTEST_
    #define MTEST__(x) printf("%d\n",x)
    #define MACRO_TEST(x)\
        printf("this is a test\n");\
        MTEST_##x    
    
    int main(void)
    {
        MACRO_TEST();
        MACRO_TEST(_(5));
        return 0;
    }
    

    EDIT

    And if 0 can be used as skip:

    #include <stdio.h>
    
    #define MACRO_TEST(x) \
        do { \
            printf("this is a test\n"); \
            if (x +0) printf("%d\n", x +0); \
        } while(0)
    
    int main(void)
    {
        MACRO_TEST();
        MACRO_TEST(5);
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-15 22:41

    The C99 standard says,

    An identifier currently defined as an object-like macro shall not be redefined by another #define reprocessing directive unless the second definition is an object-like macro definition and the two replacement lists are identical. Likewise, an identifier currently defined as a function-like macro shall not be redefined by another #define preprocessing directive unless the second definition is a function-like macro definition that has the same number and spelling of parameters, and the two replacement lists are identical.

    I think compiler prompts a warning of redefined MACRO. Hence it is not possible.

    0 讨论(0)
  • gcc and recent versions of MS compilers support variadic macros - that is macros that work similar to printf.

    gcc documentation here: http://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html

    Microsoft documentation here: http://msdn.microsoft.com/en-us/library/ms177415(v=vs.80).aspx

    0 讨论(0)
提交回复
热议问题