switch (expression)
Guy Harris
guy at gorodish.Sun.COM
Thu Jul 14 16:47:45 AEST 1988
> I don't know about casting should be avoided. I'm looking at shmop(2) manual
> page for our 3B2 (shared memory operation) and it says:
SHMOP(2), hell, look at BRK(2):
Upon successful completion, "brk" returns a value of 0 and
"sbrk" {which is a char * function} returns the old break value.
Otherwise, a value of -1 is returned...
> Somebody at AT&T must think casting a pointer to an int (or a long) isn't
> such a bad idea, unless I'm missing something (it has been known to happen).
It probably wasn't as bad an idea back when UNIX was first being done in C;
pointers and integers both fit into 16 bits on a PDP-11, so everybody "knew"
this was safe. It was still a bad idea, though; "sbrk" should have returned a
null pointer instead.
Unfortunately, we're stuck with the sins of the past, such as system calls
returning -1 even when they're returning pointers and special signal handler
values such as "(int (*)())1" (changed to "(void (*)...", which still doesn't
fix the problem in question), so C implementors on UNIX systems are obliged to
ensure that you can cast -1, 1, and maybe some other integral values to
pointers and have it "work right".
All the January 11, 1988 C draft appears to say is
3.3.4 Cast operators
...
A pointer may be converted to an integral type. The size of integer
required and the result are implementation-defined. If the space
provided is not long enough, the behavior is undefined.
An arbitrary integer may be converted to a pointer. The result is
implementation-defined.
I don't see the guarantee from K&R that "The mapping (from integer to pointer)
always carries an integer converted from a pointer back to the same pointer"
anywhere in the places I looked in the draft.
As such, I would avoid all pointer casts except the unavoidable ones (such as
the -1 to "result of 'sbrk' type" casts).
More information about the Comp.std.c
mailing list