From eggert@twinsun.com Wed Nov 6 16:34:31 1996 From: Paul Eggert Subject: Re: -32768 (Brader, RISKS-18.55) Date: Wed, 6 Nov 1996 11:32:37 -0800 Mark Brader's discussion of -32768 is correct as far as it goes, but it omits some of the more entertaining aspects of C expression evaluation. Here's a table that may help RISKS readers appreciate some of the finer points. This table uses the usual C notation: an `0x' prefix means hexadecimal; an `L' suffix means the type is `long'; `U' means `unsigned'. 2's complement arithmetic is assumed, so none of the expressions overflow. [SEE NOTE BELOW.] `*' marks disagreements with the usual mathematical meanings of expressions. C expression value of C expression, assuming: 16-bit `int' 32-bit `int' 32768 32768L 32768 0x8000 32768U 32768 -32767 - 1 -32768 -32768 -32768 -32768L -32768 -0x8000 32768U * -32768 -0x8000 == -32768 0 * 1 0U < -32767 - 1 1 * 1 * 0U < -32768 0 1 * 0 < -0x8000 1 * 0 Is everything clear now? [NOTE added, at Mark Brader's suggestion: Paul's assumption is one that is assumed for this posting only; it is not guaranteed by the language. In particular, C can be legally implemented on 1's complement hardware, where the value -32,768 is not permissible in a 16-bit int (or short) at all. MB via PGN] From Dik.Winter@cwi.nl Wed Nov 6 16:36:19 1996 From: Dik.Winter@cwi.nl Subject: Re: -32768 (Fredriksson, RISKS-18.57) Date: Wed, 6 Nov 1996 14:39:35 GMT What you are missing is that "-32768" in C is not a constant but an expression. The type of a C expression depends on the type of the operands and the operator. In this case the operand is "32768", the operator is "-". The type of 32768 is "long" if the type "int" is only 16 bits, and so the type of "-32768" is "long" in that case. But in the context of the definition of INT_MAX the type should be "int". On the other hand, when we write "-32767 - 1" the type is "int" because all constituent parts are of that type. [This item is included to close the discussion off. Bear Giles had it exactly right in his followup in RISKS-18.49, and it might have been better for me to have pointed that out privately to Kurt Fredriksson. But the error is a common one, so perhaps it was worth flogging it once more. Strong typing is the answer to a lot of questions, but it also helps to understand the questions. PGN]