Sujet : Re: size_t best practice
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.lang.cDate : 22. Aug 2024, 14:12:53
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <865xrsaega.fsf@linuxsc.com>
References : 1 2 3 4
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Ike Naar <
ike@sdf.org> writes:
On 2024-08-22, Tim Rentsch <tr.17687@z991.linuxsc.com> wrote:
>
Andrey Tarasevich <andreytarasevich@hotmail.com> writes:
>
We can immediately apply the pattern I demonstrated above to this
and get
>
for (size_t i = v->_size - 1; i != index - 1; --i)
v->_values[i + 1] = v->_values[i];
>
Done. No need for an extra safeguard.
>
Better (please ignore cosmetic layout differences):
>
for( size_t i = v->_size; i > index; i-- ){
v->_values[i] = v->_values[i-1];
}
>
Or even get rid of the for loop, and use memmove() :
>
memmove(v->_values + index + 1, v->_values + index,
(v->_size - index) * sizeof *v->_values);
Yes, although that ignores the context of the question
that was asked, about how to deal with loop index
variables in the presence of possible "underflow".