Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!taumet!steve From: steve@taumet.com (Stephen Clamage) Newsgroups: comp.lang.c Subject: Re: Casting pointers Keywords: cast Message-ID: <326@taumet.com> Date: 20 Jul 90 15:41:30 GMT References: <1614@ghost.stsci.edu> Organization: Taumetric Corporation, San Diego Lines: 29 davids@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@taumet.com