Article View: comp.std.c
Article #3457Re: (no subject) [cast expression as an lva
From: Fergus Henderson
Date: Wed, 11 Oct 1995 23:28
Date: Wed, 11 Oct 1995 23:28
47 lines
2458 bytes
2458 bytes
Steve Clamage <clamage@Eng.Sun.COM> wrote: > 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))++; The only trouble with that is that it doesn't work if `src' was declared as a `register' variable. > 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*); Indeed. The project I'm current working on contains the following code: /* ** GNU C allows lvalue casts, so if we have gcc, use them. ** If we don't have gcc, then we can use *(type *)&lval, ** but that wouldn't work for gcc since lval might be a global ** register in which case we couldn't take it's address. ** Similarly for comma expressions. */ #ifdef __GNUC__ #define LVALUE_CAST(type, lval) ((type)(lval)) #define LVALUE_SEQ(expr, lval) ((expr),(lval)) #else #define LVALUE_CAST(type, lval) (*(type*)&(lval)) #define LVALUE_SEQ(expr, lval) (*((expr),&(lval))) #endif Note that a similar issue arises with comma expressions: GNU C allows `a, b' to be used as an lvalue if `b' is an lvalue. Other compilers mostly don't, so you have to use `*(a, &b)'. But again that doesn't work if `b' is a `register' variable. (The project I'm working on uses GCC's global register variables extension for performance, so dropping the `register' qualifier is not an option.) -- Fergus Henderson | "Australia is the richest country in the world, fjh@cs.mu.oz.au | according to a new system of measuring wealth http://www.cs.mu.oz.au/~fjh | announced by the World Bank yesterday." PGP: finger fjh@128.250.37.3 | - Melbourne newspaper "The Age", 18 Sept 1995.
Technical Details
Message-ID:
<9528509.10795@mulga.cs.mu.OZ.AU>Path:
arc1-ca.pugleaf.net!munta.cs.mu.OZ.AU!fjhReferences:
<45e68p$t78@inferno.mpx.com.au> <45ef3f$n8u@engnews2.Eng.Sun.COM> <45fgea$d8j@yage.tembel.org> <KANZE.95Oct11105909@slsvgqt.lts.sel.alcatel.de>Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c,comp.lang.c,comp.unix.solaris Path: arc1-ca.pugleaf.net!munta.cs.mu.OZ.AU!fjh From: fjh@munta.cs.mu.OZ.AU (Fergus Henderson) Subject: Re: (no subject) [cast expression as an lva Message-ID: <9528509.10795@mulga.cs.mu.OZ.AU> Sender: news@cs.mu.OZ.AU (CS-Usenet) Organization: Computer Science, University of Melbourne, Australia References: <45e68p$t78@inferno.mpx.com.au> <45ef3f$n8u@engnews2.Eng.Sun.COM> <45fgea$d8j@yage.tembel.org> <KANZE.95Oct11105909@slsvgqt.lts.sel.alcatel.de> Distribution: inet Date: Wed, 11 Oct 1995 23:28:35 GMT