Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!seismo!sundc!sun!gorodish!guy From: guy%gorodish@Sun.COM (Guy Harris) Newsgroups: comp.lang.c Subject: Re: Comparing chars to constants Message-ID: <31174@sun.uucp> Date: Sun, 18-Oct-87 21:14:35 EDT Article-I.D.: sun.31174 Posted: Sun Oct 18 21:14:35 1987 Date-Received: Mon, 19-Oct-87 02:08:54 EDT References: <4663@elroy.Jpl.Nasa.Gov> Sender: news@sun.uucp Lines: 46 > On a Sun, it generates the code that is commonly expected, but on a Masscomp > is gives a warning "Comparison always false" and optimizes away the > if statement. Umm, on a Sun running 3.4, what it does is say "foo.c", line 4: warning: constant 128 is out of range of char comparison "foo.c", line 4: warning: value coerced to -128 for bug compatibility "foo.c", line 4: warning: do not expect this coercion in release 4.0 and then generate the code that is commonly, but incorrectly, expected. When it says "do not expect this coercion", it MEANS it; this WILL go away, and the behavior WILL be the same as it is on the Masscomp compiler. (You will get a warning from the compiler when it does this.) > In reading K&R I was unsure of what is to happen, under 7.6 and 7.7 it > claims that the "usual arithmetic conversions are performed". From 6.6 > both sides are converted into ints, 0x80 stays the same but if p is equal > to 0x80 it may always be sign extended on some machines depending on its > character sign convientions. Does this imply that the above comparision > is truly non-portable? You bet! It will work just fine on a 3B[2-20], since "char" is unsigned on those machines' C implementations (which means you'd better not do something such as: char c; if ((c = getchar()) == EOF) since on those machines it won't do what you might expect), but it won't work on machines on whose C implementations "char" is signed, unless they don't correctly implement the "usual arithmetic conversions" (that's why it says "bug compatibility"; it's providing bug-for-bug compatibility with compilers in earlier 3.x releases). > Both machines give the same result if it is rewritten as: > > if (p == (char)0x80) Which is what you should write here. Alternatively, you can write if (p == '\200') Guy Harris {ihnp4, decvax, seismo, decwrl, ...}!sun!guy guy@sun.com