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

Please forgive me for the bikeshedding, but I have a quick question as a C novice: Is the equality check in the following necessary?

    if (foo & 0x80 == 0x80) {
I thought if you're checking a bit simply anding would be enough (since everything else would be zeros). In other words, could we just use

    if (foo & 0x80) {
If so, then it seems like this would be the preferred form to avoid the precedence issue presented in the article.


I am seeing that as basically defensive coding. Similar to how you may do this:

  switch (mode) {
      case FOO: ... break;
      case BAR: ... break;
  }
Do you need the very last break? Technically no, but including it so that you don't forget it when you need it later can be a good idea.

(Also, I think explicitly using comparison operators in conditionals might be the idiomatic thing to do in Go. Someone correct me here if I'm wrong about that.)


The example was using C, not Go.


Aye, though the same code later appears in Go.


0x80 is 0b01010000.

Consider that (foo & 0x80) is (0x16 == 0b00010000) if foo is 0x16.

(This may or may not be the intended functionality one way or the other!)


I believe 0x80 is 0b1000000


Oops, did everything in decimal. Good point and correction. Still, the difference in legibility and implications of the two lines of code are important. Modern compilers would optimize ((foo & 0x80) == 0x80) to (foo & 0x80) but leave ((foo & 0x60) == 0x60) alone because it is testing more than one bit.




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

Search: