Archived

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

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

Recommended Posts

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

Share on other sites
> //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 on other sites
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!

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 on other sites
Just remember to put all your macros in parenthases. This, for example, shouldn''t give you problems:

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

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

1. 1
2. 2
Rutin
22
3. 3
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 11
• 9
• Forum Statistics

• Total Topics
632564
• Total Posts
3007104

×