Summary: The defined operator tests whether a name has been defined.
The test expression of an #if or #elif directive can use the defined operator to test whether a name has been defined. You can use this feature, along with #define and #undef, to turn various parts of a program on and off, compiling different parts under different conditions.
The defined operator is true if its argument has been defined and false otherwise. A name is considered defined if it has been created with #define (and not later removed with #undef).
The DEFINED.C program below prints Hi because the name DEBUG is defined when the compiler encounters the #if defined directive.
/* DEFINED.C: Demonstrate defined operator. */
#define DEBUG 12345
main()
{
#if defined( DEBUG )
printf( “Hi\n” );
#endif
}
The defined operator tests only whether a name is defined, not whether it has a certain value. Thus, the DEFINED.C program will print Hi no matter what value is assigned DEBUG. You could substitute the directive
#define DEBUG 0
to define DEBUG as 0, or the directive
#define DEBUG
to define DEBUG as having no value at all. Both directives define the name DEBUG, so the program would print Hi in both cases.
You can use the logical NOT operator (!) to reverse the logic of an #if defined directive. (For more information on logical operators, see topic .) The code
#if !defined( DEBUG )
printf( “Hi\n”);
#endif
prints Hi if DEBUG is not currently defined.
A plain #if directive treats undefined names a little differently than does an #if defined directive. If a name is not currently defined, the #if directive treats the name as having the value 0.
In the following code, the #if directive explicitly tests whether DEBUG equals 0.
#undef DEBUG
#if DEBUG == 0
printf( “Hi\n” );
#endif
The result is the same as that of the previous example.
NOTE:
The defined operator is new under the ANSI C standard. You may see older programs that use the older directives #ifdef and #ifndef for the same purpose. These directives are obsolete, but QuickC for Windows version 1.0 supports them for the sake of compatibility. The #ifdef directive is followed by a name (not in parentheses) and works the same as #if with defined. If the given name has been defined, #ifdef is true. The #ifndef directive is the opposite of #ifdef. It is true if the given name is not currently defined.