Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site dataio.UUCP Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!mhuxt!houxm!vax135!cornell!uw-beaver!uw-june!entropy!dataio!bright From: bright@dataio.UUCP (Walter Bright) Newsgroups: net.lang.c Subject: Re: Numeric comparisons Message-ID: <797@dataio.UUCP> Date: Mon, 2-Sep-85 17:11:37 EDT Article-I.D.: dataio.797 Posted: Mon Sep 2 17:11:37 1985 Date-Received: Wed, 4-Sep-85 06:43:59 EDT Reply-To: bright@dataio.UUCP (Walter Bright Organization: Data I/O Corp., Redmond WA Lines: 24 In article <693@terak.UUCP> doug@terak.UUCP (Doug Pardee) writes: >Compiler writers note -- a comparison is not "just a subtract". >For example: > >#define NBITS 16 >/* NBITS is number of bits in an integer */ > int a, b; > a = 3 << (NBITS-3); /* 24576 for NBITS=16 */ > b = -a; > if (a>b) > printf("Comparison was done by bit-wise comparison\n"); > else > printf("Comparison was done by subtraction\n"); /* WRONG */ >A compiler would have had to generate extra code to test for Overflow >in order to get the correct result. I disagree. A comparison is a subtract with the result thrown away. The trick is to select the correct conditional branch instruction afterwards, depending on whether a signed or unsigned comparison was done. The case you labeled as WRONG is wrong, a compiler that did that would have a bug, but not for the reasons you mentioned. If a or b was declared as unsigned, that case would be correct. No additional code is required to test for Overflow, that is handled by using the correct conditional branch, even if a subtract instruction was generated.