编译器指令在C++中的工作

Working of the compiler directive in C++

本文关键字:工作 C++ 指令 编译器      更新时间:2023-10-16

#define 编译器指令对我来说似乎很奇怪。我读过没有为其分配内存.

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

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

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

宏与变量不是一回事。

您的编译器将翻译程序

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

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

将名称test替换为#define语句中给出的值。您可能想看看您可以在互联网上找到的一些教程,例如:

#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;
}

实际上,test将在编译之前被代码中遇到的50替换。由于替换未在运行时完成,因此没有开销。