Stop bashing macros ---- who says they are bad?

  • Thread starter Generic Usenet Account
  • Start date
G

Generic Usenet Account

I have written a small macro that provides the relative offset of any
field within a structure. Here it goes:

#define RELATIVE_OFFSET(a,b) \
{ \
cout << "The relative offset of the " \
<< strchr(#b, '.') + 1 << " field
is " \
<< (int)&b - (int)&a << endl; \
}

usage:
RELATIVE_OFFSET(structVar, structVar.fieldName);



To all those who believe that inlining is a much better option I say
---- macros ain't that bad.

KP Bhat
 
J

Jonathan Turkanis

Generic said:
I have written a small macro that provides the relative offset of any
field within a structure. Here it goes:

Have you heard of offsetof?
 
G

Generic Usenet Account

Jonathan said:
Have you heard of offsetof?


I am extremely embarrassed to admit that I had never heard about this.
Thanks for enlightening me. This is what I love about the Usenet -----
a constant learning experience...

Bhat
 
C

Chris Croughton

I have written a small macro that provides the relative offset of any
field within a structure. Here it goes:

Well, quite apart from the fact that the offsetof() feature does it more
portably, no one says that macros are totally useless. You illustrate
one of the uses, to make a string from a name which can't be done any
other way than by #x in a macro.
To all those who believe that inlining is a much better option I say
---- macros ain't that bad.

Macros are evil, not bad. Sometimes they are the lesser of two or more
evils. The problem with them is that they are too frequently used for
situations where inline functions (and template functions) are a better
solution, often because the programmer is really still writing C instead
of C++. For instance:

template <class T>
inline T abs(const T& a)
{
return (a < 0 ? -a : a);
}

versus:

#define abs(a) (a < 0 ? -a : a)

The latter evaluates its argument twice, which causes problems if the
argument has side-effects (abs(++x) for instance), the former is
type-safe and only evaluates its argument once. It can even be
overridden with a special implementation, for instance for abs of a
string (remove a leading minus sign, or something) which isn't possible
with a macro.

Chris C
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,049
Members
47,654
Latest member
LannySinge

Latest Threads

Top