Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how is #if / #endif different than if?

Tags:

c#

I am following a tutorial that has this code:

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        int i = 1;
        while (true)
        {
#if TEST
            if (i % 2 == 0)
            continue;
#endif
            i++;
            Console.WriteLine("The value of i is {0}", i);
            if (i > 9)
                break;
            }
            Console.WriteLine("The value of i is {0}", i);

            Application.Run(new Form1());
        }

What is the purpose of using #if TEST instead of just if(TEST)?

like image 521
Alex Gordon Avatar asked Oct 05 '10 22:10

Alex Gordon


1 Answers

Because using #IF will determine if the code is compiled or not.

Using if will determine if the code is executed or not.

It seems there's an "environment" TEST that's defined in compile time. So if that environment exists, the

if (i % 2 == 0)
continue;

will be tested and executed: Only odd numbers will be printed.

The important thing to notice is that the compiled code changes depending on the existence of TEST. In a "NON-TEST environment" the

if (i % 2 == 0)
continue;

wont even exist when the application is executed.

what is the purpose of using #IF TEST instead of just if(TEST)?

TEST is not a variable, nor a constant. It doesn't even exist at run time. It is a flag passed to the compiler so it can decide on compiling some code (i.e putting it into the executable)

Maybe it would be clearer if the #if directive had something else inside. Lets modify your snippet to this:

#if TEST
            if (i == 5)
                System.exit(1)//Not a c# programmer;
#endif

In this case, under the existence of TEST, the program will only loop 5 times. On each iteration, i will be tested against 5. Wait a minute!!! It wont even compile!

If TEST is not defined, then the application will continue until another exit condition is reached. No comparison of i against 5 will be made. Read more on directives here:

#if, along with the #else, #elif, #endif, #define, and #undef directives, lets you include or exclude code based on the existence of one or more symbols. This can be useful when compiling code for a debug build or when compiling for a specific configuration.

like image 58
Tom Avatar answered Oct 05 '22 00:10

Tom