【问题标题】:Multiplication macro gives the wrong answer [duplicate]乘法宏给出了错误的答案[重复]
【发布时间】:2020-09-03 12:32:58
【问题描述】:
#include <iostream>
using namespace std;

#define MULTIPLY(a, b) a*b

int main(){
    cout << MULTIPLY(2+3, 3+5);
    return 0;
}

我预计这会打印40,因为五乘八等于四十。为什么会打印16

【问题讨论】:

  • 2 + 3 * 3 + 5 不是 40。
  • 试试这个#define MULTIPLY(a, b) ((a)*(b)),想想有什么区别。
  • 但比任何宏都好int MULTIPLY(int a, int b) { return a * b; }。宏就是魔鬼™。
  • 不要使用宏。只是不要。
  • 一个很好的说明为什么宏不好:MULTIPLY(4, "Hello"); 如果MULTIPLY 是一个函数,编译器会捕获它。

标签: c++ macros c-preprocessor


【解决方案1】:

因为 C++ 宏不是函数。它们是文本副本,这意味着:

cout << 2+3*3+5;

等于 2 + (3*3) + 5

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多