Quantcast
Channel: Hacker News 50
Viewing all articles
Browse latest Browse all 9433

ifs and &&s and Plan 9's Source Code | Computationally Endowed

$
0
0

Comments:"ifs and &&s and Plan 9's Source Code | Computationally Endowed"

URL:http://computationallyendowed.com/blog/2012/12/03/ifs-and-ands-and-plan-9s-source-code.html


ifs 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, it’s a curiosity worth noting, especially given its source.

Dec 03, 2012 if (expr1) if (expr2) stmt ≡ if (expr1 && expr2) stmt

Viewing all articles
Browse latest Browse all 9433

Trending Articles