Casting pointers
Stephen Clamage
steve at taumet.com
Sat Jul 21 01:41:30 AEST 1990
davids at stsci.EDU (David Silberberg) writes:
>Does anyone know if the following cast operation will perform correctly?
> (char *)ptr += num_chars;
>If the last line above were replaced by
> ptr = (char *)ptr + num_chars;
>it would perform as desired. Does casting work on an lvalue?
According to ANSI C, a cast is an expression, and cannot result in an
lvalue; so the original line violates the standard. Historically,
many C compilers allowed the first expression as a shorthand for the
(correct) second expression, and many program were written using that
(incorrect) shorthand. So compiler writers have been forced by
public pressure (speaking from personal experience) to allow the old
incorrect form ("my old compiler accepted this, so your crummy compiler
is no good!").
To avoid writing the left side of the assignment twice (and to continue
to use the += operator), you may also write the expression as
*(char**)(&ptr) += num_chars;
In this case, there is no improvement in clarity, but if "ptr" and
"num_chars" are complex expressions, this form may be less error-prone.
I won't argue matters of style, only matters of what is guaranteed to
be portable.
--
Steve Clamage, TauMetric Corp, steve at taumet.com
More information about the Comp.lang.c
mailing list