Computing the absolute value of an integer
Shawn H. Oesterle
oesterle at wpi.wpi.edu
Sun May 6 23:25:02 AEST 1990
In article <8977 at hydra.gatech.EDU> dsrekml at prism.gatech.EDU (Mike Mitten) writes:
>In article <1990May4.121950.22726 at agate.berkeley.edu> c60c-3cf at e260-3c.berkeley.edu (Dan Kogai) writes:
>>What's wrong with using a macro like the following
>>
>>#define abs(x) (((x) >= 0) ? (x) : -(x))
>Won't both of these macros blow up if x is a function such as:
>
> y = abs(foo(bar));
>
>or
>
> y = _abs(foo(bar));
>
That's right. That is one thing which I dislike about macros in C. For
example, take the following function which finds the height of a binary
tree.
#define max(a,b) (((a) > (b)) ? (a) : (b))
/* This function returns the height in O(n) time (n is the number of nodes) */
int TreeHeight(const TREE * tree) {
if(tree != NULL) {
int x = TreeHeight(tree->left),
y = TreeHeight(tree->right);
return(1 + max(x,y));
}
else {
return(-1);
}
}
/* because the 'max' macro has functions as its arguments, TreeHeight() is
changed from a linear time complexity function to an exponential time
complexity function! */
int TreeHeight(const TREE * tree) {
if(tree != NULL) {
return(1 + max(TreeHeight(tree->left), TreeHeight(tree->right)));
}
else {
return(-1);
}
}
BTW, C++ resolves this problem with the 'inline' keyword for function
declarations.
--
Shawn Oesterle { oesterle at wpi.wpi.edu } antherea
"...I tend to think that there are only two kinds of people in
the world anyway: those that oversimplify and those that don't." -Jim Northrup
More information about the Comp.lang.c
mailing list