I have started reading the Lions Commentary on Unix v6. I came across these snippets, which I have never seen used in the C language. The author does provide some sort of an explanation, but could someone explain to me what is happening here?
params.h
:
SW 0177570
......
struct { int integ; };
and this used in unix/prf.c
if(SW->integ == 0)
Explanation by the author
SW
is defined previously as the value 0177570. This is the kernel address of a read only processor register which stores the setting of the console switch register. The meaning of the statement is clear: get the contents at location 0177570 and see if they are zero. The problem is to express this in C. The codeif (SW == 0)
would not have conveyed this meaning. ClearlySW
is a pointer value which should be dereferenced. The compiler might have been changed to acceptif (SW-> == 0)
but as it stands, this is syntactically incorrect. By inventing a dummy structure, with an elementinteg
, the programmer has found a satisfactory solution to his problem.
My question mainly is how does this work? When the compiler sees SW->integ
, how does it associate SW
with the anonymous structure?
IIRC, ancient C compilers kept all field names (such as integ
) in a single namespace instead of creating a namespace per struct
type. They also did not distinguish between struct
pointers and int
pointers, so that every pointer has an integ
field corresponding to its first sizeof(int)
bytes. Since integ
is the first value in a struct
and has type int
, SW->integ
corresponds to *((int *)SW)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With