What is the function of #if false in C #? [duplicate]

13

I'm working on a project and I saw code blocks with this with #if false :

What'sthedifferencetothis(commentedvs#iffalse)?

    
asked by anonymous 08.03.2018 / 15:20

3 answers

17

The #if is a preprocessor directive that allows you to pass parameters to the compiler.

When you do

#if false
 ...
#endif

The compiler understands that not is to compile / interpret the block of #if .

A more common use of this directive is:

#if DEBUG
    Console.WriteLine("Olá mundo!");
#endif

That will execute the block only if the project is in DEBUG mode.

The #if false directive does not work as a comment.

Within the comment you do not need to respect the syntax of C #, for example, the% comp_confirm causes the compiler to delete all of that compile block but does not ignore it completely equal to a comment, so the compiler will still look at the text inside the block.

For example, the code below will generate an error:

#if false
 #foo
#endif

    
08.03.2018 / 15:32
6

In your case none, the result will be the same. However many code refactoring / analysis tools can mark comments in the code as a code smells (which it actually is).

Thinking about compiling your code, the directive (#IF) is interpreted even before the lexical analysis begins, and it will be analyzed whether that code will be used in the Build process (I need sources to confirm this). In your case since the condition is always false, it will not be part of the build.

The comment will be ignored at the time that the lexical parsing reads trying to create known tokens.

    
08.03.2018 / 15:40
6

Conditional Compilation

#IF is a precompile command. With it you can modify your code according to parameters (constants) that you set or use predefined constants such as DEBUG or TRACE .

If you open the project build options window you will see a window similar to this:

As you can see, in the conditional symbols box I've registered a constant called MINHA_CONSTANTE . This way I can create a type code:

#IF MINHA_CONSTANTE
     ... código que vai compilar apenas quando essa constante estiver definida
#ENDIF

And this way when you want, you can go to the build tab and remove this constant or add others and your code will compile according to that logic you defined.

That's why a #IF false does not make much sense and it does the same job as commenting the code, since that snippet will not be compiled.

    
08.03.2018 / 17:40