#506 – Using Expressions in #if and #elif Directives

You can use more complex expressions in #if and #elif directives, instead of just checking to see whether a single conditional compilation symbol is defined.

In the example below, the #elif directive triggers if the DOGSBARK symbol is defined and then DOGSGROWL symbol is not defined.

#define DOGSBARK
//#define DOGSWAG
//#define DOGSGROWL

using System;
using DogLibrary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Dog d = new Dog("Kirby", 12);

#if DOGSWAG
            d.WagTail();
#elif DOGSBARK && !DOGSGROWL
            d.Bark();
#else
            d.BarkAndGrowl();
#endif

        }
    }
}

You can build more complex expressions using parentheses and the && (logical AND) and || (logical OR) operators.

#if (DOGSWAG && DOGSDOTRICKS) || (DOGSDOEVERYTHING)
            d.WagAndFetch();
#endif
Advertisements

#505 – Using the #elif Directive

When you check whether a conditional compilation symbol is defined using the #if, #else and #endif directives, you can include additional clauses within the scope of the #if directive by using the #elif directive.  The #elif directive adds an additional expression to check, if any earlier expressions evaluate to false.

In the example below, we check both the DOGSBARK and the DOGSWAG symbols to determine which line to compile.

//#define DOGSBARK
#define DOGSWAG

using System;
using DogLibrary;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            Dog d1 = new Dog("Kirby", 12);
#if DOGSBARK
            d1.Bark();
#elif DOGSWAG
            d1.WagTail();
#else
            d1.JustSitThere();
#endif
        }
    }
}


You can include as many #elif clauses as you like.

#499 – Conditional Compilation Symbols Are Defined or Undefined

At any given point in your source code, while the compiler is compiling that section of code, a particular conditional compilation symbol is either defined or undefined.

You define a conditional compilation symbol

  • Using the #define preprocessor directive
  • Using the /define option on the compiler command line
  • Implicitly (for DEBUG and TRACE symbols), when selecting a build option for a project

You undefine a conditional compilation symbol

  • Using the #undef preprocessor directive
  • When reaching the end of a source file

A conditional compilation symbol is either defined or undefined–it has no value.

You check whether a conditional compilation symbol is defined by using the #if or #elif preprocessor directives.

A conditional compilation symbol remains defined in a source file until the end of the containing source file or until encountering an #undef directive (whichever comes first).