F
Frederick Gotham
I'd like to discuss the use of signed integers types where unsigned integers
types would suffice.
A common example would be:
#include <cassert>
#include <cstddef>
int CountOccurrences(unsigned char const val,
unsigned char const p[],
std::size_t const len)
{
assert(len >= 2);
unsigned char const * const p_over = p + len;
int i = 0; /* USE OF SIGNED INTEGER TYPE */
do
{
if(val == *p++) ++i;
}
while(p != p_over);
return i;
}
Firstly, I tend to shy away from signed integer types wherever possible
primarily because overflow results in undefined behaviour.
Another aspect I'd like to discuss though is efficiency. If a machine uses
two's complement, then there should be no difference in adding positive
numbers and negative numbers.
However, for machines which use something other than two's complement, would
there be overhead in adding signed integers? For instance something like:
int i = 5;
int j = -4;
if( j >= 0 )
{
/* Add using a particular technique */
}
else
{
/* Add using a particular technique */
}
When adding unsigned integers, there would be no need for that.
Would I be right in thinking that there could be an efficieny issue with
using signed integer types on machines which don't use two's complement, or
would I be way off the mark?
types would suffice.
A common example would be:
#include <cassert>
#include <cstddef>
int CountOccurrences(unsigned char const val,
unsigned char const p[],
std::size_t const len)
{
assert(len >= 2);
unsigned char const * const p_over = p + len;
int i = 0; /* USE OF SIGNED INTEGER TYPE */
do
{
if(val == *p++) ++i;
}
while(p != p_over);
return i;
}
Firstly, I tend to shy away from signed integer types wherever possible
primarily because overflow results in undefined behaviour.
Another aspect I'd like to discuss though is efficiency. If a machine uses
two's complement, then there should be no difference in adding positive
numbers and negative numbers.
However, for machines which use something other than two's complement, would
there be overhead in adding signed integers? For instance something like:
int i = 5;
int j = -4;
if( j >= 0 )
{
/* Add using a particular technique */
}
else
{
/* Add using a particular technique */
}
When adding unsigned integers, there would be no need for that.
Would I be right in thinking that there could be an efficieny issue with
using signed integer types on machines which don't use two's complement, or
would I be way off the mark?