Sujet : Re: Computer architects leaving Intel...
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.archDate : 05. Sep 2024, 23:04:14
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <86h6atoizl.fsf@linuxsc.com>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Terje Mathisen <
terje.mathisen@tmsw.no> writes:
[...]
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.
>
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.e I cannot easily replicate a downward loop that exits when the
counter become negative:
>
for (int i = START; i >= 0; i-- ) {
// Do something with data[i]
}
See below.
One of my alternatives are
>
unsigned u = start; // Cannot be less than zero
if (u) {
u++;
do {
u--;
data[u]...
} while (u); /* presumably the } was intended */
}
This code isn't the same as the for() loop above. If start is
0, the for() loop runs once, but the do..while loop runs zero times.
Regarding the given for() loop, namely this:
for (int i = START; i >= 0; i-- ) {
// Do something with data[i]
}
If START is signed (presumably of type int), so the loop might run
zero times, but never more than INT_MAX times, then
for( unsigned u = START < 0 ? 0 : START + 1u; u > 0 && u--; ){
// Do something with data[i]
}
If START is unsigned, so in all cases the loop must run at
least once, then
unsigned u = START;
do {
// Do something with data[i]
} while( u > 0 && u-- );
(Yes I know the 'u > 0' expressions can be replaced by just 'u'.)
The optimizer should be smart enough to realize that if 'u > 0'
is true then the test 'u--' will also be true. The same should
hold if 'u > 0' is replaced by just 'u'.
(Disclaimer: code not compiled.)