preprocessor over conditional statements
I have never worked with #if , #ifdef , #ifndef , #else , #elif and #endif .
As I was going through some source-codes, I found an extensive use of these directives. Did some reading on conditional-preprocessors but found no clue like how are they different from normal conditional statements . So I was wondering what is the advantage of following code:
#include<iostream>
int main()
{
int i = 0;
#if i == 0
std::cout<<"This";
#else
std::cout<<"That";
#endif
return 0;
}
over this:
#include<iostream>
int main()
{
int i = 0;
if (i == 0)
std::cout<<"This";
else
std::cout<<"That";
return 0;
}
Also, when to-use /not-to-use conditional-preprocessor?
Conditional preprocessor doesn't work like in your first example.
It's working with constants, you see? At compile time, it looks at the various conditions and puts in/omits source code according to it.
For example:
#define HAS_COMPARISON
int main() {
#ifdef HAS_COMPARISON
int i = 0;
if(i == 0) std::cout << "This";
else
#else
std::cout << "That";
#endif
}
With the define
set, it will set the variable i
and perform the comparison...in short, it will output This
. If you comment that define, the entire block will not be in your program which means that it will always output That
, without ever setting the variable or doing the comparison.
That's the most common use of preprocessor defines. You can also define values and compare those to have variable behaviour with the same define, but that's another issue.
Once more: Conditional preprocessor is evaluated at compile time, variable conditions are evaluated at runtime.
The example you showed doesn't seem helpful due to lack of other information. But here's an example that #if
is useful.
#if OS == LINUX
//do something
#elif OS == SOLARIS
//do something else
#else
//
#endif
The key is that #if
is evaluated in compile time, but if
is evaluated when program runs.
#if BYTE_ORDER == LITTLE_ENDIAN
//do something
#else
//do something else
#endif
The use of the preprocessor directives in this case is not entirely useful. But the use of these preprocessor directives is useful in many other cases.
These preprocessor directives can be used for conditional compilation. eg If some program has to be developed for multiple platforms then platform-specific constants can be given values. Changing these values compilation specific to the platform can be done while the whole code can be maintained as one big entity.
These are also useful while debugging. Test units can be compiled into the code and ran by using these conditional compilations while debugging and they can be stopped from compiling using these.
链接地址: http://www.djcxy.com/p/29426.html上一篇: 按钮文字将Firefox中的填充删除
下一篇: 通过条件语句预处理器