Liste des Groupes | Revenir à c arch |
David Brown wrote:Loop counters can usually be signed or unsigned, and it usually makes no difference. Array indices are also usually much the same signed or unsigned, and it can feel more natural to use size_t here (an unsigned type). It can make a difference to efficiency, however. On x86-64, this code is 3 instructions with T as "unsigned long int" or "long int", 4 with "int", and 5 with "unsigned int".On 05/09/2024 11:12, Terje Mathisen wrote:Loop counters of the for (i= 0; i < LIMIT; i++) type are of course fine with unsigned i, arrays always use a zero base so in Rust the only array index type is usize, i.e the largest supported unsigned type in the system, typically the same as u64.David Brown wrote:>Unsigned types are ideal for "raw" memory access or external data, for anything involving bit manipulation (use of &, |, ^, << and >> on signed types is usually wrong, IMHO), as building blocks in extended arithmetic types, for the few occasions when you want two's complement wrapping, and for the even fewer occasions when you actually need that last bit of range.>
That last paragraph enumerates pretty much all the uses I have for integer-type variables, with (like Mitch) a few apis that use (-1) as an error signal that has to be handled with special code.
>
You don't have loop counters, array indices, or integer arithmetic?
unsigned arithmetic is easier than signed integer arithmetic, including comparisons that would result in a negative value, you just have to make the test before subtracting, instead of checking if the result was negative.I can't follow that at all. Unsigned and signed arithmetic and comparisons both work simply and as you'd expect. /Mixing/ signed and unsigned types can get things wrong.
I.e I cannot easily replicate a downward loop that exits when the counter become negative:A more important thing is that the first version, with signed i, is /vastly/ simpler and clearer in the source code.
for (int i = START; i >= 0; i-- ) {
// Do something with data[i]
}
One of my alternatives are
unsigned u = start; // Cannot be less than zero
if (u) {
u++;
do {
u--;
data[u]...
while (u);
}
This typically results in effectively the same asm code as the signed version, except for a bottom JGE (Jump (signed) Greater or Equal instead of JA (Jump Above or Equal, but my version is far more verbose.
Alternatively, if you don't need all N bits of the unsigned type, then you can subtract and check if the top bit is set in the result:Or you could just write sane code that matches what you want to say.
for (unsigned u = start; (u & TOPBIT) == 0; u--)
Terje
Les messages affichés proviennent d'usenet.