By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,652 Members | 1,466 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,652 IT Pros & Developers. It's quick & easy.

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

P: n/a
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

Jul 23 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Generic Usenet Account wrote:
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?
To all those who believe that inlining is a much better option I say
---- macros ain't that bad.

KP Bhat

Jul 23 '05 #2

P: n/a
Jonathan Turkanis wrote:
Generic Usenet Account wrote:
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?

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

Jul 23 '05 #3

P: n/a
On 17 Feb 2005 13:09:19 -0800, Generic Usenet Account
<us****@sta.samsung.com> wrote:
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
Jul 23 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.