What problems might the following macro bring to the application?

前端 未结 6 2042
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 02:50

Can the following macro bring problems?

#define sq(x) x*x

If yes, then how and why?please help.

6条回答
  •  生来不讨喜
    2021-01-27 03:11

    I'm not going to give you a straight answer (this looks like a homework question), but I'm going to give you an example that will hopefully make you think about it and come up with a correct answer:

    #include 
    
    #define sq_macro(x) x * x
    
    int sq_function(int x)
    {
        return x * x;
    }
    
    int print_and_ret(int x)
    {
        std::cout << x << '\n';
        return x;
    }
    
    int main()
    {
        std::cout << "Calling sq_macro:\n";
        sq_macro(print_and_ret(10));
    
        std::cout << "Calling sq_function:\n";
        sq_function(print_and_ret(10));
    }
    

    When you run the program, the macro and the function give two different behaviors. Think about what a macro is, and what a function is.

提交回复
热议问题