Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The way that C expresses it elegantly is via the comparison operator. The author is concerned that people try to be clever and use subtraction instead. Here is how the author corrected this error by using comparison operators instead of subtracting (in the tree man page):

    int
    intcmp(struct node *e1, struct node *e2)
    {
  -	  return (e1->i - e2->i);
  +	  return (e1->i < e2->i ? -1 : e1->i > e2->i);
    }
The ternary operator is necessary, because in C a relational operator is evaluated to 0 (false) or 1 (true). So, the author added a special case for returning a negative value (indicating the first argument should be sorted before the second).


An alternative without the ternary is

  return (e1->i > e2->i) - (e1->i < e2->i);


My C's a little rusty, but isn't the exact integer returned by the comparison undefined? Isn't is just defined as just zero or non-zero?

Therefore i would argue this is just as risky as the original solution, and that it's better to use the ternary operator


No, the relational operators (<, >, <= and >=) are defined to evaluate to either 0 or 1, and the result has type int.

The same is true of the equality operators (= and !=), the logical negation operator (!), and the logical boolean operators (&& and ||).

There are other C idioms based on this, like !!expr to squash a zero-or-non-zero expression down to zero-or-one.


Regardless of the correctness of the code, if it's not obvious and you need to explain it, you probably should not write it (unless you have profile data that makes you do otherwise).

"Programs must be written for people to read, and only incidentally for machines to execute."


I think that particular example should be obvious to anyone whose C isn't "a little rusty".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: