Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Tim Rentsch
Newsgroups: comp.lang.c
Subject: Re: size_t best practice
Date: Thu, 22 Aug 2024 06:12:53 -0700
Organization: A noiseless patient Spider
Lines: 29
Message-ID: <865xrsaega.fsf@linuxsc.com>
References: <86ed6h9cxm.fsf@linuxsc.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Injection-Date: Thu, 22 Aug 2024 15:12:54 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="dd674af37156d5461d600da65dab9de0";
logging-data="476774"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX194zwPwTDRUDJRV2n4FPaW1o9sCXNzQDwk="
User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Cancel-Lock: sha1:tNAnSKReC+okjdiJAY+awugjeqQ=
sha1:iI9QFH8xw/4Ba9lPu9LeIDoSnCs=
Bytes: 1964
Ike Naar writes:
> On 2024-08-22, Tim Rentsch wrote:
>
>> Andrey Tarasevich 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".