开发者

Anonymous Structures in C found in Unix Kernel

开发者 https://www.devze.com 2023-01-18 21:58 出处:网络
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 som

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 t开发者_Python百科his 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号