Archived

This topic is now archived and is closed to further replies.

Helpful MACRO's

This topic is 5899 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

> //Finds the square of x
> #define sqr(x) (x)*(x)
> //Determines the absolute value of x
> #define absval(x) (x)<(0)?-(x)x)

I would not recommend these. E.g. consider the following code:

int a, b, c;

a = sqr(b++);
c = absval (randbetween(-10, 10));

In the first example b is incremented twice and the output is not generally a square, while the second one can generate a negative number.

It''s better either to use functions (which can be inlined) or to write your macros so the arguments are not referenced more than once.


Share this post


Link to post
Share on other sites
Can template functions be inlined? If so, then this would be the ultimate solution:

inline template T sqr( T x )
{
return (x * x);
}

inline template T absval( T x )
{
return ((x < 0) ? -x : x);
}

EDIT: Made the "class T" show-up. Thanks Oluseyi!

Edited by - Scarab0 on October 19, 2001 7:15:40 PM

Share this post


Link to post
Share on other sites
quote:
Original post by Scarab0
Can template functions be inlined?

Yes. I've written template classes with inline methods, so you're code is right.

Oh, and to make that <class T> show up, use &-lt and &-gt without the hyphen.

Edit: one of mine didn't show up either.

Edited by - Oluseyi on October 19, 2001 5:32:02 PM

Share this post


Link to post
Share on other sites
quote:
Original post by TerranFury
Just remember to put all your macros in parenthases. This, for example, shouldn''t give you problems:

#define sqr(x) ((x)*(x))

No, this is still not safe, as johnb pointed out above. Consider the following:
  
int a = 2;
int a_square = sqr(++a);

the ''sqr'' macro invocation will expand to:
  
int a_square = ((++a)*(++a))

a_square will now hold one of the values 9, 12 or 16 depending on the compiler implementation and a will hold the value 4. Not quite what you would expect just by looking at the code.

Oluseyi: That should be &lt; and &gt; for < and > respectively (I know it was just a typo).

Share this post


Link to post
Share on other sites