Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cornell!batcomputer!davidra From: davidra@batcomputer.tn.cornell.edu (David Rabson) Newsgroups: comp.lang.c Subject: "arithmetic if":: Re: Feature for the next C version Message-ID: <8515@batcomputer.tn.cornell.edu> Date: 28 Jul 89 20:53:16 GMT References: <55480@tut.cis.ohio-state.edu> <1989Jul20.152935.14872@utzoo.uucp> <67@motto.UUCP> <18764@mimsy.UUCP> <1389@crdgw1.crd.ge.com> Reply-To: davidra@tcgould.tn.cornell.edu (David Rabson) Organization: Cornell Theory Center, Cornell University, Ithaca NY Lines: 71 C does have a generalized "arithmetic if," if you wish, although it is not functionally equivalent. Switch...case...case...default is generally implemented as a table of branching addresses if the cases are integers fairly close to each other and if there are enough cases to make it pay. Both gcc and Sun's cc do this if there are at least four cases with contiguous integer tests (for instance, -1, 0, 1, and 2). Neither does it if the cases are just -1, 0, and 1; I assume someone calculated the tradeoff and found that the repeated tests were cheaper. If your variable takes on values other than +/-1 and 0, of course, you will not want to use switch...case...case to implement the arithmetic goto. As for using the results of a single TEST for two branch-if's, our FORTRAN compiler does not do this; perhaps the trick fails on a 68000, or maybe the compiler writers were too lazy to save the extra nanosecond. I think it's fairly obvious which of these pieces of code looks better. (This is probably unnecessary, but I rarely get to exercise my FORTRAN. Can anyone explain the error in the code?) EXHIBITS: PROGRAM MAIN C C NANOSECOND-WISE (MAYBE ON SOME MACHINES) BUT HOUR-FOOLISH C INTEGER I READ(5,200) I 200 FORMAT(I) IF (I) 1,2,3 1 WRITE(6,100) 100 FORMAT(20H0IT'S LESS THAN ZERO ) GOTO 4 2 WRITE(6,101) 101 FORMAT(10H0IT'S ZERO ) GOTO 4 3 WRITE(6,102) 102 FORMAT(23H0IT'S GREATER THAN ZERO ) 4 STOP END C by the way, on my machine this program doesn't even work -- if C I type in a positive number or zero, it gets it right, but if I C type any negative number, it says it's zero. main() { int i; scanf("%d",&i); if(i<0) printf("It's less than zero\n"); else if(!i) printf("It's zero\n"); else printf("It's greater than zero\n"); /* or alternatively */ printf("It's%s zero\n", i?(i<0?" less than":" greater than"):""); }