"arithmetic if":: Re: Feature for the next C version

David Rabson davidra at batcomputer.tn.cornell.edu
Sat Jul 29 06:53:16 AEST 1989


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"):"");
}



More information about the Comp.lang.c mailing list