Simple ways to disable parts of code

后端 未结 14 1152
误落风尘
误落风尘 2021-01-31 08:59

This isn\'t a typical question to solve a specific problem, it\'s rather a brain exercise, but I wonder if anyone has a solution.

In development we often need to disable

14条回答
  •  悲&欢浪女
    2021-01-31 09:16

    Sometimes i use this approach to just not overbloat the code by infinite sequence of if-endif definitions.

    debug.hpp

    #ifdef _DEBUG
        #define IF_DEBUG(x) if(x)
    #else
        #define IF_DEBUG(x) if(false)
    #endif
    

    example.cpp

    #include "debug.hpp"
    
    int a,b, ... ,z;
    
    ...
    
    IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
        // set of asserts
        assert(... a ...);
        assert(... b ...);
        ...
        assert(... z ...);
    }
    

    This is not always effective, because compiler may warn you about unused variables has used inside such disabled blocks of code. But at least it is better readable and unused variable warnings can be suppressed for example like this:

    IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
        // set of asserts
        assert(... a ...);
        assert(... b ...);
        ...
        assert(... z ...);
    }
    else {
        (void)a;
        (void)b;
        ....
        (void)z;
    }
    

    It is not always a good idea, but at least helps to reorganize the code.

提交回复
热议问题