How do you create a debug only function that takes a variable argument list? Like printf()

后端 未结 14 2091
心在旅途
心在旅途 2020-12-23 09:44

I\'d like to make a debug logging function with the same parameters as printf. But one that can be removed by the pre-processor during optimized builds.

<
14条回答
  •  囚心锁ツ
    2020-12-23 10:25

    This is how I do debug print outs in C++. Define 'dout' (debug out) like this:

    #ifdef DEBUG
    #define dout cout
    #else
    #define dout 0 && cout
    #endif
    

    In the code I use 'dout' just like 'cout'.

    dout << "in foobar with x= " << x << " and y= " << y << '\n';
    

    If the preprocessor replaces 'dout' with '0 && cout' note that << has higher precedence than && and short-circuit evaluation of && makes the whole line evaluate to 0. Since the 0 is not used the compiler generates no code at all for that line.

提交回复
热议问题