簡體   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