Advertisement

Helpful MACRO's

Started by October 19, 2001 01:59 AM
5 comments, last by Ciphersoftware 23 years, 3 months ago
Hey, I was just wondering, what are some helpful macro''s that you guys find yourselves constantly using? Heres my two bits: //Finds the square of x #define sqr(x) (x)*(x) //Determines the absolute value of x #define absval(x) (x)<(0)?-(x)x) Ciphersoftware website

Support the open source community

Ciphersoftware website

Support the open source community

> //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.


John BlackburneProgrammer, The Pitbull Syndicate
Advertisement
Yep inline will be better, but typed, you must use overloading
inline int sqr( int x )
{
return x*x;
}
inline float sqr( float x )
{
return x*x;
}

Why English rules?? C pas très malin tout ça!
_______________
Jester, studient programmerThe Jester Home in French
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

Dirk =[Scarab]= Gerrits
Just remember to put all your macros in parenthases. This, for example, shouldn''t give you problems:

#define sqr(x) ((x)*(x))
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 &ltclass 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
Advertisement
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).

This topic is closed to new replies.

Advertisement