Sujet : Re: size_t best practice
De : ike (at) *nospam* sdf.org (Ike Naar)
Groupes : comp.lang.cDate : 18. Aug 2024, 09:38:13
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <slrnvc3cnk.obv.ike@iceland.freeshell.org>
References : 1
User-Agent : slrn/1.0.3 (Patched for libcanlock3) (NetBSD)
On 2024-08-18, Mark Summerfield <
mark@qtrac.eu> wrote:
Many C std. lib. functions accept and/or return size_t values esp. for
arrays incl. char* strings.
>
In view of this I'm using size_t throughout my code for array sizes and
indexes.
>
However, this means I have to be very careful never to decrement a size_t of
value 0, since, e.g., size_t size = 0; size--; results in size ==
18446744073709551615.
>
So I need to guard against this. Here is an example I'm using
(without the assert()s):
>
[...]
>
for (size_t i = v->_size - 1; i >= index; --i) {
v->_values[i + 1] = v->_values[i];
if (!i) // if i == 0, --i will wrap!
break;
}
Substitution: j = i + 1
for (size_t j = v->_size; j > index; --j) {
v->_values[j] = v->_values[j - 1];
}