【问题标题】:Working of the compiler directive in C++ [duplicate]C ++中编译器指令的工作[重复]
【发布时间】:2014-12-09 16:13:26
【问题描述】:

#define 编译器指令对我来说似乎很奇怪。我读到没有分配内存给它。

#include <iostream>
#define test 50
int main()
{
    cout<<test;
   return 0;
}

即使没有为编译器指令#define 分配内存,上述函数也会显示 50

编译器是如何知道 50 存储在其中(测试)而没有任何内存的。

【问题讨论】:

  • 宏在编译时执行简单的文本替换。出现“test”的所有地方,编译器都会替换为“50”。所以程序的工作方式与您编写cout&lt;&lt;50; 完全相同
  • 另外,因为这是 C++,所以你真的应该使用 const int test = 50;。我们在标准化 C++ 时努力工作以使 #define 几乎没有必要。

标签: c++ compiler-directives


【解决方案1】:

Macros 与变量不同。

你的编译器会翻译程序

#include <iostream>
#define test 50
int main()
{
   cout << test;
   return 0;
}

#include <iostream>
int main()
{
   cout << 50;
   return 0;
}

通过将名称 test 替换为您在 #define 语句中给出的值。您可能想查看一些可以在 Internet 上找到的 tutorials,例如:

#define getmax(a,b) ((a)>(b)?(a):(b))

这将替换任何出现的 getmax 后跟两个参数 通过替换表达式,但也将每个参数替换为其 标识符,正如你所期望的,如果它是一个函数:

// function macro
#include <iostream>
using namespace std;

#define getmax(a,b) ((a)>(b)?(a):(b))

int main()
{
  int x=5, y;
  y= getmax(x,2);
  cout << y << endl;
  cout << getmax(7,x) << endl;
  return 0;
}

【讨论】:

  • 内容丰富:) 肯定会看一些教程!
【解决方案2】:

实际上,test 将被 50 替换为在编译之前之前在代码中遇到的任何位置。因为替换不是在运行时完成的,所以没有开销。

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 2017-01-05
    • 2013-10-09
    • 2011-07-18
    • 2011-03-02
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多