Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!necntc!ames!oliveb!sun!gorodish!guy From: guy%gorodish@Sun.COM (Guy Harris) Newsgroups: comp.lang.c Subject: Re: pointer cast question Message-ID: <28558@sun.uucp> Date: Sat, 19-Sep-87 23:15:29 EDT Article-I.D.: sun.28558 Posted: Sat Sep 19 23:15:29 1987 Date-Received: Sun, 20-Sep-87 20:01:00 EDT References: <100@teletron.UUCP> Sender: news@sun.uucp Lines: 37 Keywords: pointer cast alignment > Why is this the case? It seems to me that the cast should produce code > which aligns the pointer to a proper alignment boundary if necessary. Except that this would mean that the pointer in question, after having been "rounded up" or "rounded down" so to speak, would no longer point to the location you thought it would point to. > The compiler should hide such a machine dependant thing from the programmer. So? The compiler can't hide all the nasty details of the outside world from programmers. If you want to write machine-independent code, don't cast pointers. If you want to write machine-dependent code, go ahead, but take responsibility for the consequences; be prepared for this code not to work on machines other than the ones you wrote it for. > What is the purpose of such a cast (other than to make lint happy) if not > to convert a valid data value of one type to a valid data type of another? OK, on a byte-addressible machine with 4-byte "int"s that disallows off-boundary references to quantities longer than one byte (such as the machine on which this message is being typed), how would you convert the value of a "char *" containing the bit pattern "0xfeffffc1" into an "int *"? Leave it alone? That would make it an invalid pointer. Use the value of an "int *" containing the bit pattern "0xfeffffc0" or "0xfeffffc4"? That would mean you wouldn't be pointing to "the 'int' at location 0xfeffffc1", i.e. the 4-byte quantity with one end at location "0xfeffffc1" and the other end at location "0xfeffffc5". If the pointer in question is guaranteed not to be misaligned (e.g., pointers returned by "malloc"), it would be wasteful to adjust the pointer. If it is not guaranteed to be misaligned, you have the two choices above, neither of which gets you what you want. As such, compilers generally take the "path of least resistance" and make portable or reasonable-though-nonportable code work, at the expense of making more *outr\'e* types of code not work. Guy Harris {ihnp4, decvax, seismo, decwrl, ...}!sun!guy guy@sun.com