Problem with ()?():() as ending test in for-loop

Tom Karzes karzes at mfci.UUCP
Fri May 26 03:43:46 AEST 1989


In article <20658 at news.Think.COM> barmar at kulla.think.com.UUCP (Barry Margolin) writes:
}In article <1200 at liszt.kulesat.uucp>vanpetegem at liszt.kulesat.uucp writes:
}}The code with which I am in trouble, goes as follows:
}}
}}	 for(n = 1;  ((n % 10) ? (k > 2) : (n < 100));  n++)
}}                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}}           {
}}             ..... (in some expressions k is changed, depending on n)
}}	   }
}}
}}What I want to do is simply perform the test (k > 2) as ending test for the
}}"for-loop", except in the cases where n is dividable by 10. In the latter
}}situation the test (n < 100) has to be done.
}
}The sense of the test clause of your :? expression is wrong.  When n
}is divisible by 10, (n % 10) is 0, and 0 represents "false" in C.  I
}would write your end test as
}
}	((n % 10) == 0) ? (k > 2) : (n < 100)
}
}although "real C programmers" would probably write it as
}
}	(n % 10) ? (n < 100) : (k > 2)
}
}i.e. they would just interchange the true and false clauses, taking
}advantage of the fact that the result of the % can be used as a
}boolean.


Rubbish.  His code should do exactly what he said he wanted it to do.
He said he wants to perform the test (k > 2), EXCEPT in the cases where
n is "dividable" by ten, in which case he wants to use (n < 100).  In
other words, he wants (k > 2) when n is NOT divisable by 10, and (n < 100)
when n is divisable by 10.  Now "n is not divisable by 10" is equivalent
to ((n % 10) != 0).  So he wants:

    (((n % 10) != 0) ? (k > 2) : (n < 100))

which is equivalent to:

    ((n % 10) ? (k > 2) : (n < 100))

which is exactly what he wrote.  When n is NOT divisable by 10, (n % 10)
is non-zero (i.e., true) and you get (k > 2).  When n is divisable by 10,
(n % 10) is zero (i.e., false) and you get (n < 100).

Assuming there isn't any wrong with parts of the code that weren't included
in the original article, it appears that he has encountered a compiler bug.



More information about the Comp.lang.c mailing list