C++ defines macros
- C++ macros are very useful, especially in places like logging systems.
- Macros are used during precompilation and can replace anything in the code.
- Macros are very useful, but don't overuse them, because it may make your code unreadable to others.
Here are a few examples of macro usage:
#include <iostream>
// 定义一个宏
#define WAIT std::cin.get()
int main()
{
WAIT;
}
#include <iostream>
// 定义一个宏
#define LOG(x) std::cout << x << std::endl
int main()
{
LOG("Xwp is handsome");
}
This is great, you can specify some code not to participate in compilation
When I #define PR_DEBUG 1
: means that LOG(x)
this macro is valid, and then output information;
when I #define PR_DEBUG 0
: means that LOG(x)
this macro is meaningless, and no information will be output.
#define PR_DEBUG 0
#if PR_DEBUG == 1
#define LOG(x) std::cout << x << std::endl
#else
#define LOG(x)
#endif
int main()
{
LOG("xwp is handsome");
LOG(8);
}
In addition, the definition of the macro must be on one line. If you want to write in a new line, you need to use\
#include <iostream>
#define MAIN int main() \
{
\
std::cout << 3 << std::endl;\
}
MAIN