在C/C++程序中怎麼打印一個變量的名稱呢?利用#
,看代碼:
#include <iostream>
#define VNAME(value) (#value)
int main(int argc, char *argv[]) {
float a = 0.2;
int b = 1;
std::string sss = "hello";
std::string strName = VNAME(sss);
std::cout << VNAME(a) << std::endl;
std::cout << VNAME(b) << std::endl;
std::cout << VNAME(sss) << std::endl;
std::cout << strName << std::endl;
return 0;
}
打印結果是:
a
b
sss
sss
完美解決。
分析原因:在宏VNAME中,我們使用了#
,這個#
出現在宏中,表示對後面的變量替換的時候,用雙引號""
括起來,剛好滿足我們的需求。