Conditional compilation directives for C #

Source: Internet
Author: User

The conditional compilation directive has the following four types:

#if

#elfi

#else

#endif

These conditional compilation directives are used to conditionally include or exclude part of a program segment. They have a similar effect to the IF statement in C #. You can use the logical operator with (&&) in the instruction, or (| |) and take the inverse operator (!) Wait The order in which they appear in the program must be this:

A #if statement (must have)

0 or more #elif statements

0 or a #else statement

A #endif statement (must have)

Here are some examples to illustrate their use.

#define Debug
Class Class1
{
#if Debug
void Trace (String s) {}
}
Another example:

#define A
#define B
#undef C
class D
{
  #if c
    void F () {}
  #elif A && b
  void I () {}< c9/> #else
     void G () {}
  #endif
}

It is not difficult to see that the actual compilation of the effect is equivalent to:

Class C
{
void I () {}
}
In this example, please note the use of the #elif directive, which means: "Else if", using #elif can add one or more branches to the #if instruction.

#if指令可以嵌套使用, for example:

#define DEBUG  //debugging on

#undef Trace  //tracing off

class Purchase Transaction
{
  void Commit () {
    #if Debug
      checkconsistency ();
      #if Trace
          WriteToLog (this. ToString ());
      #endif
    #enfif
    commithelper ();
  }

Preprocessing directives are not executed if they appear in the middle of other output-output elements. For example, the following program tries to show Hello World when debug is defined, otherwise the hello everyone is displayed, but the result is a laugh and cry:

Program Listing 8-6:

Using System;
Class Hello
{
 static void Main () {
    System.Console.WriteLine (@ "Hello,
 #if Debug
 World #else
     everyone
 #endif
     ");
 }
The output of the program is as follows:

Hello,
#if Debug World
#else
  everyone
#endif
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.