What does Z["ack"] = 5 mean?

Randal L. Schwartz @ Stonehenge merlyn at intelob.intel.com
Thu Oct 6 05:54:13 AEST 1988


In article <10283 at dartvax.Dartmouth.EDU>, earleh at eleazar (Earle R. Horton) writes:
| What happened here was that Z was initialized to (char)0 by the
| compiler or loader on the VAX.  (BSD 4.3)  Then, Z["ack!"] was taken
| to mean 0["ack!"] which of course means 0[<address of "ack!">].  The
| equivalence sets the first character in "ack!" equal to 5, which is
| what you see in the core dump as displayed by emacs.
| 
| This is of course grossly implementation dependent, and uses
| questionable programming practices, to wit:  Casting of char to
| pointer is highly questionable.  Said pointer defaulting to (char *)
| is probably reliable, but not good programming practice.  Assuming you
| can write on top of constant data may not work on all systems.  The
| assumption that Z will be equal to '\0' if not explicitly initialized
| is not portable.  Worse, you cannot cast a pointer ("ack!") to an
| integer array subscript on some systems!

I disagree.  I don't have the C bible to quote, but as a fluent C-er,
I can safely say that somewhere it says

   A[B] is entirely equivalent to B[A], both being synonymous with
   *(A+B)

This means that

   Z["Ack!"]

is the same as

   "Ack!"[Z]

so Z is being used as a char cast into an integer (can you say,
"subscript"?) while "Ack!" provides a const char array reference
(L-value).

Now, you may not like the idea of the subscript transposed with the
array name, but it is legal C.

The bad part is assigning into the const char array.  Some Cs will
like it, and others won't.  Essentially, what you are doing is:

   "Ack!"[0] = 5

or

  *"Ack!" = '\5'

Enough said.  Flames about how "foo" is a const char array are
welcome.  I don't know enough ANSI to comment on legality in the "new"
C.
-- 
Randal L. Schwartz, Stonehenge Consulting Services (503)777-0095
on contract to BiiN Technical Information Services (for now :-),
in a former Intel building in Hillsboro, Oregon, USA
<merlyn at intelob.intel.com> or ...!tektronix!inteloa[!intelob]!merlyn
Standard disclaimer: I *am* my employer!



More information about the Comp.lang.c mailing list