Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!samsung!uakari.primate.wisc.edu!ames!ncar!husc6!m2c!wpi!oesterle From: oesterle@wpi.wpi.edu (Shawn H. Oesterle) Newsgroups: comp.lang.c Subject: Re: Computing the absolute value of an integer Keywords: absolute, abs(), fabs() Message-ID: <12710@wpi.wpi.edu> Date: 6 May 90 13:25:02 GMT References: <11679@june.cs.washington.edu> <1990May4.121950.22726@agate.berkeley.edu> <8977@hydra.gatech.EDU> Reply-To: oesterle@wpi.wpi.edu (Shawn H. Oesterle) Organization: Worcester Polytechnic Institute, Worcester, MA Lines: 57 In article <8977@hydra.gatech.EDU> dsrekml@prism.gatech.EDU (Mike Mitten) writes: >In article <1990May4.121950.22726@agate.berkeley.edu> c60c-3cf@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@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