Conditional/ternary Statement

Forrest Gehrke,2C-119,7239,ATTBL feg at clyde.ATT.COM
Thu Feb 8 05:26:45 AEST 1990


Well I managed to mangle this question despite looking
at it several times.  Here is another try, hopefully
with my example conditional macro stated as I meant
it to be:

I recently came across this unusual (to me, anyway)
use of the conditional statement using more than one
ternary operators  ?:
It was in the form of a macro:

#define Sgn(x)  ((x) == 0 ? 0 : (x) > 0 ? 1 : -1)

Which would determine whether the subsituted variable
was equal to zero, and if not, whether more or less
than zero; consequently the sign would be known.

Now suppose one were sorting among unsigned ints from
0 to 4.  Would this be kosher?

#define Srt(x)  ((x) == 0 ? 0 : (x) < 2 ? 1 : (x) < 4 ? 3 : 4)

It would seem to be valid, but only if exited immediately
at the first true test.  If kosher, are there any speed 
advantages over a series of  if-else, or case statements?

(I realize that a pitfall might occur if the value range
of the tested variables were less than zero or more
than 4--this is just a conjured example and is really
a question whether multiple ternary operators may be 
used in a single statement).

Forrest Gehrke feg at clyde.ATT.COM



More information about the Comp.lang.c mailing list