Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Structures in C found in Unix Kernel

Tags:

c

unix

structure

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 code if (SW == 0) would not have conveyed this meaning. Clearly SW is a pointer value which should be dereferenced. The compiler might have been changed to accept if (SW-> == 0) but as it stands, this is syntactically incorrect. By inventing a dummy structure, with an element integ , 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?

like image 500
woodstok Avatar asked Oct 07 '10 11:10

woodstok


1 Answers

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).

like image 57
Fred Foo Avatar answered Oct 28 '22 09:10

Fred Foo