On 21/01/2017 11:21, Alf P. Steinbach wrote:
> On 21.01.2017 11:12, JiiPee wrote:
>> I hear experts all the time saying "dont use macros". But in my real
>> coding I see benefits sometimes using them. One is debugging/tracing
>> values in a debug mode:
>>
>>
>> Trace(x != 8, "x is wrong");
>>
>>
>> Using macro seems to be the only way to do this trace so that the
>> release version ignores that line and does not compile it. How would
>> "dont-use-macros" person do this other way?
>>
>
> There is no practical alternative to a macro for that, for example
> because you then risk a stream of silly-warnings about dead code etc.,
> warnings that you otherwise wouldn't want to disable.
But its not only about getting those trace-warnings but its also that
they slow down the runtime. Think about tracing that 10 milliona times
per second...
>
> That said there is tendency to think that since a macro must be
> involved in this case, everything should be done with macros, like
> it's macros or not macros, sort of George Bush-land: either you're
> with us, for everything, or you're with the enemy, for everything.
hehe
you have a point. Yes, I agree... and also the same thing I would say
with discussion with C-programmers. They say sometimes: "NONE of that
C++ is good at all... only C is good!!". But then C++ programmer can
also say: "everything must be C++, dont use functions , use
classes....always!!". I think its just that what works is
good....Although I dont see reason to use pure-old C only.. why not use
consts and those things?
>
> Instead I suggest limiting the use of macros to the things that macros
> are needed for, which in the above case are
>
> • Code elimination when the checking is undesired (e.g. in release
> builds).
>
> • Picking up the source location.
>
> For the latter it can IMO be a good idea to define a class that
> represents a source location, with a macro to create an instance.
>
> I guess what I'm saying is the age old advice of separating concerns
> also when it comes to use of macros. Don't think that because macros
> evidently are needed, the whole problem area is macro-land. There are
> just some pieces of the problem that require macros: these basic
> special purpose macros can support much functionality that doesn't
> need to also be expressed as macros.
yes.
Also I found handy that that macro itself does not need to contain
variables but can be just a function call:
#define Trace(matrix) TraceFunc(matrix);
// and for release:
#define Trace
So intead of putting the matrix code inside the macro, we can just make
a normal function (TraceFunc) and call it from the macro. I think better
like this. so now:
int v=9;
Matrix m;
Trace(m);
...
Trace is only done for debug. otherwise we get TraceFunc(m);