TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: KURT KUZBA
from: BOB STOUT
date: 1997-07-13 01:53:00
subject: Signs of numbers

On , Kurt Kuzba (1:154/750@fidonet) wrote: 
 > int sgn(int x)
 > {
 >    return x ? (x > 0) ? 1 : -1 : 0;
 > }
 >    It might even be better as a macro.
 > #define sgn(x) (x ? (x > 0) ? 1 : -1 : 0)
Kurt...
  I was about to chastise you over two things, when it finally dawned on me 
that I only needed to chastise you over one! ;-) The obvious one is that the 
macro implementation is "unsafe" since the operand may be evaluated twice. 
Passed an argument such as (val++), the results will probably not be what is 
expected.
  The other issue is a little knottier. You're quite correct that the type of 
the argument shouldn't matter. In the code I posted, I made a big deal of the 
type of the argument, which really shouldn't matter. In any case, you're 
comparing to zero which should work the same regardless of the type. Still, 
the issue remains in C++ that such a function *must* have a prototype and the 
prototype will be different depending on the type of the operand.
  The bottom line is that a single function...
int sgn(double x)
{
      if (x > 0.0)
            return 1;
      if (x < 0.0)
            return -1;
      else  return 0;
}
...would work just fine in C, but in C++, either a template implementation or 
overladed functions would be best. In any case, using a single function 
taking any type of integral operand *should* generate a warning when passed a 
FP operand. 
--- QM v1.00
---------------
* Origin: MicroFirm : Down to the C in chips (1:106/2000.6)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.