C macro, something weird

后端 未结 2 1486
清歌不尽
清歌不尽 2020-12-22 14:01

Trying to figure out something simple in a C macro, like this code for example:

#include  
#define MACRO(b)  printf(\"%d\\n\", b*b)

int main(         


        
相关标签:
2条回答
  • 2020-12-22 14:57

    When you use the macro, the preprocessor replaces it and its arguments quite verbatim, so the macro expansion in your code will look like

    printf("%d\n", 4+1*4.1);
    

    That will not provide you with the result you want, and it is one of the reasons that function-like macros are looked down upon.

    You need to use parentheses to make sure this problem doesn't occur:

    #define MACRO(b)  printf("%d\n", (b)*(b))
    

    while will then result in the following expansion:

    printf("%d\n", (4+1)*(4.1));
    

    Whenever you have problems with something preprocessor related, there are options for just about all compilers to stop after the preprocessing stage, which allows you to look at the preprocessed source and which will help you with problems like this.


    Also note that another possible problem here is if the expression you pass as argument to the macro is e.g. a function call with some side-effect that function will be called twice and the side-effect will be happen twice, even when using parentheses.

    A simple example, using your macro:

    int my_function(void)
    {
        printf("Foo\n");
        return 1;
    }
    
    int main(void)
    {
        MACRO(my_function());
    }
    

    The above program will print "Foo\n" twice. If MACRO was a proper function the call to my_function would only happen once and the printout from the function would only happen once.

    0 讨论(0)
  • 2020-12-22 15:04

    Put parentheses around your macro to evaluate arguments in the correct order:

    #include <stdio.h> 
    #define MACRO(b)  printf("%d\n", (b)*(b))
    
    int main()
    {
        MACRO(4+1); 
    }
    
    0 讨论(0)
提交回复
热议问题