1

Sorry if this is duplicate, but I can not find good answer.

I have code like this:

int cmp(size_t const a, size_t const b){
  return (int) b - (int) a;
}

I am worrying of overflow. How function must be written in correct way?

I do not need correct value, I need result to be int and to keep at least the sign, e.g. negative / positive / zero.

I also want to avoid any branching such those:

int cmp(size_t const a, size_t const b){
  if (a == b)
     return 0;
  else
     return a < b ? -1 : +1; 
}
Nick
  • 9,962
  • 4
  • 42
  • 80
  • ptrdiff is pointer difference? I want result to be int. – Nick Jul 17 '17 at 13:33
  • 3
    You could use a branch-less compare function using `return (a > b) - (a < b);`. See the accepted answer to https://stackoverflow.com/questions/10996418/efficient-integer-compare-function/10997428#10997428. – R Sahu Jul 17 '17 at 13:37
  • @RSahu - I do exactly that, but I am thinking if there are better solution – Nick Jul 17 '17 at 13:39
  • 1
    that seems to be the most efficient solution, without risking integer overflow -- at least at SO. – R Sahu Jul 17 '17 at 13:40
  • @RSahu Thanks. I thought you can do something better with bit masks. – Nick Jul 17 '17 at 13:44

0 Answers0