The #define
is part of the preprocessor language for C and C++. When they're used in code, the compiler just replaces the #define
statement with what ever you want. For example, if you're sick of writing for (int i=0; i<=10; i++)
all the time, you can do the following:
#define fori10 for (int i=0; i<=10; i++)
// some code...
fori10 {
// do stuff to i
}
If you want something more generic, you can create preprocessor macros:
#define fori(x) for (int i=0; i<=x; i++)
// the x will be replaced by what ever is put into the parenthesis, such as
// 20 here
fori(20) {
// do more stuff to i
}
It's also very useful for conditional compilation (the other major use for #define
) if you only want certain code used in some particular build:
// compile the following if debugging is turned on and defined
#ifdef DEBUG
// some code
#endif
Most compilers will allow you to define a macro from the command line (e.g. g++ -DDEBUG something.cpp
), but you can also just put a define in your code like so:
#define DEBUG
Some resources:
- Wikipedia article
- C++ specific site
- Documentation on GCC's preprocessor
- Microsoft reference
- C specific site (I don't think it's different from the C++ version though)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…