Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!sq!msb From: msb@sq.UUCP Newsgroups: comp.lang.c Subject: Re: ANSI C awkward examples Message-ID: <1987Nov27.020914.11888@sq.uucp> Date: Fri, 27-Nov-87 02:09:14 EST Article-I.D.: sq.1987Nov27.020914.11888 Posted: Fri Nov 27 02:09:14 1987 Date-Received: Sun, 29-Nov-87 14:41:02 EST References: <1470@copper.TEK.COM> Reply-To: msb@sq.UUCP (Mark Brader) Organization: SoftQuad Inc., Toronto Lines: 42 Checksum: 37154 > unsigned int u = 4000000000; /* Assume 32 bit int and long */ > (u + 1) > 50 is true; but > (u + 1L) > 50 is false. This is fixed in the new draft (November 9, 1987). The "usual arithmetic conversions" now specify that when "long" and "unsigned" meet up, the conversion is to "unsigned long" if "long" and "int" are the same size, and to "long" otherwise. > 2) This code fragment is not portable in ANSI C: > u_long = u_char_1 * u_char_2; As discussed at some length in this group just a little while ago, multiplying two ints to get a long is indeed dangerous in terms of overflow. If you don't want overflow, cast one or both operands to "long", or in this case "unsigned long", before multiplying. Incidentally, in email following from that past discussion, Doug Gwyn pointed out a subtlety in the Draft's specification that I hadn't noticed. Since the behavior of signed integer types on overflow is undefined, it IS permissible for short i, j; /* assume 16 bits */ long p; /* assume 32 bits */ p = i*j; to behave the same as p = (long)i*(long)j; instead of like the commonly expected p = (long) (short) (i*j); This is contrary to what most of us responding to the original article said, including me. However, this does not mean that it's permissible on overflow for the result to spill over into any other object (even if p was also short). I presume that if you really want the truncating behavior the last example form above will suffice. But if the types were "unsigned short" and "unsigned long", then the behavior on overflow would be well-defined, and the analog of the last example form would indeed be required. Mark Brader "C takes the point of view SoftQuad Inc., Toronto that the programmer is always right" utzoo!sq!msb, msb@sq.com -- Michael DeCorte