繁体   English   中英

C++ 中的宏参数评估

[英]Macros argument evaluation in C++

我不明白宏不只评估一次参数(如内联函数)而是每次在代码中使用它的原因是什么。

例如:

(示例取自这里: https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp?view=msvc-170

在这段代码中有一个宏:


// 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


与此代码相比,使用等效的内联 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 );
}

宏不是很聪明。 他们只是在编译开始之前执行文本替换

编码:

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

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

指示预处理器更改此代码,并将其交给编译器:

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

您可以观察到toupper被定义的表达式替换,而每次出现的a都被作为宏参数传递的任何文本替换。 它不是一个值或一个表达式——它只是文本。

从您观察到的问题中,您可能还会发现编译器错误会显示此替换代码。 在源文件中看不到的代码。

暂无
暂无

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

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