Hacker News new | ask | show | jobs
by gmartres 4873 days ago
Here's a real implementation of prettyprint without conditional jumps (this assumes signed right shifts are implemented as arithmetic shifts by your compiler, but everyone does that anyway):

  #include <stdio.h>
  #include <stdint.h>
  
  void prettyprint(int a, int b)
  {
      int lt_mask = (a-b) >> (sizeof(int) * 8 - 1);
      intptr_t lt = (intptr_t)"%d is < %d\n";
      intptr_t ge = (intptr_t)"%d is >= %d\n";
      char *text = (char*) (lt & lt_mask) + (ge & ~lt_mask);
      printf(text, a, b);
  }
  
  int main(int argc, char **argv)
  {
      prettyprint(atoi(argv[1]), atoi(argv[2]));
      return 0;
  }
The point is that the CPU doesn't have to guess what to execute next, so https://en.wikipedia.org/wiki/Branch_misprediction cannot happen.

And if what you're interested in is using the call stack to keep track of executed code, a more effective approach would be to convert the program to CPS, see https://en.wikipedia.org/wiki/Continuation-passing_style and http://matt.might.net/articles/cps-conversion/ .