How do you use #define?

前端 未结 8 815
鱼传尺愫
鱼传尺愫 2020-12-11 15:03

I\'m wondering about instances when it makes sent to use #define and #if statements. I\'ve known about it for a while, but never incorporated it into my way of coding. How e

相关标签:
8条回答
  • 2020-12-11 15:33

    In C# #define macros, like some of Bernard's examples, are not allowed. The only common use of #define/#ifs in C# is for adding optional debug only code. For example:

            static void Main(string[] args)
            {
    #if DEBUG
                //this only compiles if in DEBUG
                Console.WriteLine("DEBUG")
    #endif 
    #if !DEBUG
                //this only compiles if not in DEBUG
                Console.WriteLine("RELEASE")
    #endif
                //This always compiles
                Console.ReadLine()
            }
    
    0 讨论(0)
  • 2020-12-11 15:38

    @Ed: When using C++, there is rarely any benefit for using #define over inline functions when creating macros. The idea of "greater speed" is a misconception. With inline functions you get the same speed, but you also get type safey, and no side-effects of preprocessor "pasting" due to the fact that parameters are evaluated before the function is called (for an example, try writing the ubiquitous MAX macro, and call it like this: MAX(x++, y).. you'll see what I'm getting at).

    I have never had to use #define in my C#, and I very rarely use it for anything other that platform and compiler version checking for conditional compilation in C++.

    0 讨论(0)
提交回复
热议问题