Article View: comp.std.c
Article #3450Re: (no subject) [cast expression as an lva
From: Steve Clamage
Date: Tue, 10 Oct 1995 18:47
Date: Tue, 10 Oct 1995 18:47
55 lines
2620 bytes
2620 bytes
In article t78@inferno.mpx.com.au, msmith@jolt.mpx.com.au (Michael Smith) writes: >Life is hard... and then you die. (Ronald.Tschalaer@psi.ch) wrote: >: Morgan Herrington wrote: >: > >: > Daniel Wood <dwood> writes: >: > >: > > The following: >: > > ((char *)src)++; /* src is an (int *) */ > > >I **THINK** that this was considered legal using K&R1 style C. K&R1 said that a cast yielded a value, not an lvalue. The PCC compiler did not check for this violation, and the code it generated happened to do what the programmer intended. A generation of programmers grew up thinking the code was valid, since compilers didn't complain and the code worked. I don't know what would have happened if the programmer wrote float f; (double)f = 10.0; /* will the compiler complain? */ long l; (short)l = 5; /* how about this? */ Some compilers (including some I worked on) detected the error of trying to use the result of a cast as an lvalue. Complaints from users about how the compilers broke their code and they didn't care what ANSI said resulted in the compilers allowing the code anyway -- at least in non-strict mode. > It's not >legal as ANSI C but many compilers let you get away with it. When you've >got 2000 or so lines of poorly documented spagetti code using such >constructs and the code works flawlessly then it is a tough decision to >order a re-write. Yes. If you want to sell compilers, you have to make reasonable compromises to keep customers happy. >When 64KB was a lot of memory, an XT was fast and a Vax 11/750 was a >monster, people used to write some ugly code. These days we can afford a >few extra bytes to make code readable. What's interesting is that you can get the same effect with valid code that should generate the same object code as the invalid original. For example, instead of ((char*)src)++; you can write (*(char**)(&src))++; I don't claim this code is more readable, but you could encapsulate the ugliness in a macro. For example: #define increment_as(ptr, T) ((*(T*)(&ptr))++) increment_as(src, char*); --- Steve Clamage, stephen.clamage@eng.sun.com
Technical Details
Message-ID:
<45ef3f$n8u@engnews2.Eng.Sun.COM>Path:
arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!usenetReferences:
<45e68p$t78@inferno.mpx.com.au>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!engnews2.Eng.Sun.COM!usenet From: clamage@Eng.Sun.COM (Steve Clamage) Newsgroups: comp.std.c,comp.lang.c,comp.unix.solaris Subject: Re: (no subject) [cast expression as an lva Date: 10 Oct 1995 18:47:11 GMT Organization: Sun Microsystems Inc. Distribution: inet Message-ID: <45ef3f$n8u@engnews2.Eng.Sun.COM> References: <45e68p$t78@inferno.mpx.com.au> Reply-To: clamage@Eng.Sun.COM NNTP-Posting-Host: taumet.eng.sun.com