What is the use and when to use the preprocessor directives?

5

At some point I had seen the use of #define in C #. Today I searched about this and found its documentation here, but not answered all my doubts.

Code sample with preprocessor directives:

#define DEBUG  

#if DEBUG  
    Console.WriteLine("Debug version");  
#endif

Given this, my doubts are:

  • What are preprocessor directives for?
  • When should I use preprocessor directives?
asked by anonymous 28.07.2017 / 17:23

1 answer

5

They serve a lot of things, each serves a different thing. They serve to change the behavior of the compiler in a certain stretch.

You should use it whenever you need to change the build. It almost never exists in normal codes. In fact they should be avoided until there is no better solution. And C # has few. It actually has the #region directive that does not change the build and helps the organization in the IDE, and many consider this a language error .

Passing all is a very broad question. You have some questions about it:

The #if determines whether the code inside it will be compiled or ignored. This is decided if a compile variable, which has nothing to do with code variables, exists. In general, these variables are defined as arguments in the compiler. In C # it is rare to need to create a variable with #define , in some cases another piece can generate conditionally. This was heavily used in C because language was not powerful and needed almost any other language to help create what was wanted. Even today, C needs less of that, and C ++ can eliminate almost completely.

In the example shown the code will be compiled because the variable was created just above, which does not even make sense in real code.

So there you go to compile sections conditionally. You actually have other ways to resolve it to debug code that does not need the policy .

    
28.07.2017 / 17:50