Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Implementation of the abs() function [o.t.]

Author: Dieter Buerssner

Date: 10:35:02 07/07/03

Go up one level in this thread


On July 07, 2003 at 10:34:53, Robert Hyatt wrote:

>On July 06, 2003 at 14:05:03, Omid David Tabibi wrote:
>
>>On July 06, 2003 at 13:12:25, Robert Hyatt wrote:

>>>#define abs(x)    ((x<0) ? -x : x)

>>What's the difference between the above macro and the function
>>
>>int simple_abs (int i) {
>>    return (i >= 0) ? i : -i;
>>}
>>
>>when inlined?
>
>No difference that I know of, if you have inlining enabled.

Why do you think this? See for example my answer to Omid's question. Some
problems with the macro can be fixed, by putting the argument x into
parentheses.

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

As you stated it, for example abs(a+b) will fail (-a+b is in general not
-(a+b)). The problem with the sideeffects cannot be fixed in Standard C. In many
cases, slowness, cannot be fixed; for example the compiler may not be able to
find out, that a function call has no sideeffect.

abs(slow_func_with_no_side_effect(a))

Similar cases, when the argument includes (volatile) global vars.

The function version has no problem. At least with slightly modern compilers, it
should be best to use the abs() provided by the compiler in most cases. The only
reason, that comes into mind, that C has this abs() at all, is that it may be
done fast by tricks (provided by the compiler), that are not available in pure C
code.

Regards,
Dieter




This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.