if
s and &&
s and Plan 9's Source Code
It’s not every day that you come across code that makes you feel funny because of its unusual syntactic structure; code that makes you sit and stare for a moment and wonder, Will it parse? There just aren’t that many Duff’s Devices out there. Yet when I came across Plan 9‘s source code and started poking around in cp.c, I did a double-take when I saw this function:
int
samefile(Dir *a, char *an, char *bn)
{
Dir *b;
int ret;
ret = 0;
b=dirstat(bn);
if(b != nil)
if(b->qid.type==a->qid.type)
if(b->qid.path==a->qid.path)
if(b->qid.vers==a->qid.vers)
if(b->dev==a->dev)
if(b->type==a->type){
fprint(2, "cp: %s and %s are the same file\n", an, bn);
ret = 1;
}
free(b);
return ret;
}
What makes this code look odd is the lack of indentation of nested statements, and the omission of brackets. I quickly identified that as the source of my funny feeling, and then its meaning became clear. The author of this function is using if
statements to conjoin several expressions. I think this more readable than the alternative of using the &&
operator to conjoin the expressions in a single if
statement. Most programmers won’t be familiar with the pattern, so despite my aesthetic judgement, I’m not going to use it in code that other people have to see and maintain.
Still, its a curiosity worth noting, especially given its source.