C #define macros

后端 未结 7 1327
情书的邮戳
情书的邮戳 2020-12-21 06:59

Here is what i have and I wonder how this works and what it actually does.

#define NUM 5
#define FTIMES(x)(x*5)

int main(void) {
    int j = 1;
    printf(\         


        
相关标签:
7条回答
  • 2020-12-21 07:00

    the preprocessor substitutes all NUM ocurrences in the code with 5, and all the FTIMES(x) with x * 5. The compiler then compiles the code.

    Its just text substitution.

    0 讨论(0)
  • 2020-12-21 07:01

    And if you want to fix it:

    #define FTIMES(x) ((x) * 5)
    
    0 讨论(0)
  • 2020-12-21 07:03

    define is just a string substitution.

    The answer to your question after that is order of operations:

    FTIMES(j+5) = 1+5*5 = 26

    FTIMES((j+5)) = (1+5)*5 = 30

    0 讨论(0)
  • 2020-12-21 07:05

    Since it hasn't been mentioned yet, the way to fix this problem is to do the following:

    #define FTIMES(x) ((x)*5)
    

    The parentheses around x in the macro expansion prevent the operator associativity problem.

    0 讨论(0)
  • 2020-12-21 07:12

    The reason this happens is because your macro expands the print to:

    printf("%d %d\n", j+5*5, (j+5)*5);
    

    Meaning:

    1+5*5 and (1+5)*5
    
    0 讨论(0)
  • 2020-12-21 07:24

    Order of operations.

    FTIMES(j+5) where j=1 evaluates to:

    1+5*5

    Which is:

    25+1

    =26

    By making FTIMES((j+5)) you've changed it to:

    (1+5)*5

    6*5

    30

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