Hacker News new | ask | show | jobs
by taneq 525 days ago
Does the C compiler optimise out the branch from the if() statement?

I'd write it more like this:

    int main(int argc, char **argv) {
      int total = 0;
      for (int i=2147483647; i; --i) {
        total += i & 1;
      }
      printf("%d\n", total);
      return 0;
    }
2 comments

> Does the C compiler optimise out the branch from the if() statement?

In a function as simple as this, the existence of a branch may be as fast or faster than a version without as the CPU has the opportunity to eliminate register/memory modification via branch prediction.

So even if a compiler does not optimize out this particular if construct, there is a good chance the CPU will.

You inverted the condition and the loop doesn't go to 0, so that's not functionslly the same code.