Skip to main content
Code Review

Return to Answer

Commonmark migration
Source Link

###Overflow bug###

Overflow bug

You shouldn't do sign(a-b) because the value of a-b could overflow and give you the wrong sign value. For example, if a were 0x80000000 (a negative number) and b were 1, you would find a sign of 1 instead of -1. You should instead compare a against b directly. For example you could use the compare() function from Toby Speight's answer:

int compare(T a, T b = {})
{
 // This is a "clever" way of determining the sign. Some
 // compilers recognise this idiom and reduce it to a single
 // instruction.
 return (a > b) - (a < b);
}

###Overflow bug###

You shouldn't do sign(a-b) because the value of a-b could overflow and give you the wrong sign value. For example, if a were 0x80000000 (a negative number) and b were 1, you would find a sign of 1 instead of -1. You should instead compare a against b directly. For example you could use the compare() function from Toby Speight's answer:

int compare(T a, T b = {})
{
 // This is a "clever" way of determining the sign. Some
 // compilers recognise this idiom and reduce it to a single
 // instruction.
 return (a > b) - (a < b);
}

Overflow bug

You shouldn't do sign(a-b) because the value of a-b could overflow and give you the wrong sign value. For example, if a were 0x80000000 (a negative number) and b were 1, you would find a sign of 1 instead of -1. You should instead compare a against b directly. For example you could use the compare() function from Toby Speight's answer:

int compare(T a, T b = {})
{
 // This is a "clever" way of determining the sign. Some
 // compilers recognise this idiom and reduce it to a single
 // instruction.
 return (a > b) - (a < b);
}
Source Link
JS1
  • 28.8k
  • 3
  • 41
  • 83

###Overflow bug###

You shouldn't do sign(a-b) because the value of a-b could overflow and give you the wrong sign value. For example, if a were 0x80000000 (a negative number) and b were 1, you would find a sign of 1 instead of -1. You should instead compare a against b directly. For example you could use the compare() function from Toby Speight's answer:

int compare(T a, T b = {})
{
 // This is a "clever" way of determining the sign. Some
 // compilers recognise this idiom and reduce it to a single
 // instruction.
 return (a > b) - (a < b);
}
lang-cpp

AltStyle によって変換されたページ (->オリジナル) /