#ifdef vs #if - which is better/safer as a method for enabling/disabling compilation of particular sections of code?

后端 未结 19 855
忘了有多久
忘了有多久 2020-11-30 17:26

This may be a matter of style, but there\'s a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter...

Basically, we have some de

19条回答
  •  佛祖请我去吃肉
    2020-11-30 18:03

    My initial reaction was #ifdef, of course, but I think #if actually has some significant advantages for this - here's why:

    First, you can use DEBUG_ENABLED in preprocessor and compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using #if, I can write this

      DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000);
    

    ... instead of ...

    #ifdef DEBUG_MODE
      DoSomethingSlowWithTimeout(5000);
    #else
      DoSomethingSlowWithTimeout(1000);
    #endif
    

    Second, you're in a better position if you want to migrate from a #define to a global constant. #defines are usually frowned on by most C++ programmers.

    And, Third, you say you've a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that #if is the preferred choice means that code using #ifdef will compile -and run- even when DEBUG_ENABLED is false. And it's much easier to track down and remove debug output that is produced when it shouldn't be than vice-versa.

    Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your #define, and because the value is a single lexical token, it's the one time you don't need parentheses around it.

    #define DEBUG_ENABLED true
    

    instead of

    #define DEBUG_ENABLED (1)
    

提交回复
热议问题