As others have already written: it does not matter for the CPU. Signed and unsigned commands take the same time. Some operations in unsigned arithmetic are even easier to carry out and may require a smaller cycle than the signed version (single-bit division is one example).
However, this is only half the story.
C ++ defines counter integer overflows as undefined behavior and unsigned integers as modulo2. This offers completely different optimization options that lead to different code.
One example:
int foo (int a) { return a * 1000 / 500; } unsigned bar (unsigned a) { return a * 1000 / 500; }
Here foo can be optimized for:
int foo (int a) { return a * 2; }
And the bar will remain the same.
Note that mathematically these two functions are the same, but they start to give different results if the argument exceeds INT_MAX / 1000.
Since the effect of signed overflows is undefined, the compiler has the right to simply pretend that INT_MAX is not used when it comes to simplifying expressions. For unsigned arithmetic, this is not the case, and the compiler must emit code that performs multiplication and division. This, of course, is slower than the optimized version.
Note. Most compilers are conservative when it comes to such optimizations and only allow them if you request them because they tend to break code checking and overflows. Other compilers, especially in the embedded and DSP worlds, always do such optimizations even at low levels of optimization. The programmers who write for these machines know the subtle details, so this is rarely a problem.
OTOH we discussed stories in which C / C ++ programmers fall into this trap more than once in stackoverflow.
source share