samedi 21 janvier 2017

preprocessor debug print : avoid calculation of "operator+" for output string when debug==false

I just learned preprocessor lately and love how it make the debug process can be easier.

Here is how I utilize preprocessor to debug in my existing code base.
I have already used it in various places.

Version 1

Vector.h

#define VECTOR_DEBUG true

//inside a function
#if(VECTOR_DEBUG)
    if(vector.size()==0){
        //Passing this line = I am sure there are something wrong
        Util::print("cannot normalize "+ Util::toString(object.id));

    }
#endif

This works very good.

Advantage:- (#X)

  • If VECTOR_DEBUG == false, vector.size() will be not called (optimized out).
  • If VECTOR_DEBUG == true but vector.size()!=0, both function (Util::toString and string::operator+) will not be called. (determined at run-time)

Version 2

(Main objective) Then, I want to improve it to be more concise, i.e. one line, like this:-

debug_print(HERE_DEBUG,vector.size()==0,"cannot normalize "+ Util::toString(object.id));

Here is how debug_print is defined :-

#define debug_print(preFlag,locFlag, paramString ) \
     do { if (preFlag&&locFlag) Util::print(paramString); } while (0)

It is modified from a thread.

This solution doesn't has advantage #X.

Question

How to improve version 2 to have both advantages (#X) as in version 1?
I want 1-line usage.

Note:-

  • I don't mind some performance penalty in debug mode (when VECTOR_DEBUG == true),
    ... but I care the performance of the released program (when VECTOR_DEBUG == false).

  • I prefer the concatenation of string to still use + (not << or ,),
    ... even it may waste some CPU cycles.
    (I feel like home when use +.)

Aucun commentaire:

Enregistrer un commentaire