简体   繁体   English

C++ 中的宏参数评估

[英]Macros argument evaluation in C++

I don't understand what is the reason that macros don't evaluate their argument only once (like inline functions), but each time it is used in the code.我不明白宏不只评估一次参数(如内联函数)而是每次在代码中使用它的原因是什么。

For example:例如:

(the example is taken from here: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp?view=msvc-170 ) (示例取自这里: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp?view=msvc-170

In this code there is a macro:在这段代码中有一个宏:


// inline_functions_macro.c
#include <stdio.h>
#include <conio.h>

#define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a))

int main() {
   char ch;
   printf_s("Enter a character: ");
   ch = toupper( getc(stdin) );
   printf_s( "%c", ch );
}
//  Sample Input:  xyz
// Sample Output:  Z


Compared to this code, with the equivalent inline function:与此代码相比,使用等效的内联 function:

// inline_functions_inline.cpp
#include <stdio.h>
#include <conio.h>

inline char toupper( char a ) {
   return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a );
}

int main() {
   printf_s("Enter a character: ");
   char ch = toupper( getc(stdin) );
   printf_s( "%c", ch );
}

Macros are not very smart.宏不是很聪明。 They simply perform text substitution before compilation begins.他们只是在编译开始之前执行文本替换

The code:编码:

#define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a))

int main() {
   char ch = toupper( getc(stdin) );
}

Instructs the preprocessor to change this code and instead hand this to the compiler:指示预处理器更改此代码,并将其交给编译器:

int main() {
   char ch = ((getc(stdin)) >= 'a' && ((getc(stdin)) <= 'z') ? ((getc(stdin))-('a'-'A')):(getc(stdin)));
}

You can observe that toupper was replaced by the defined expression, while every occurance of a is replaced by whatever text was passed as the macro parameter.您可以观察到toupper被定义的表达式替换,而每次出现的a都被作为宏参数传递的任何文本替换。 It's not a value or an expression - it's just text.它不是一个值或一个表达式——它只是文本。

Asde from the problems you observe, you may also discover that compiler errors will show this substituted code.从您观察到的问题中,您可能还会发现编译器错误会显示此替换代码。 Code that you don't see in your source file.在源文件中看不到的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM