Deutsch English Français Italiano |
<20240818123649.00007b53@yahoo.com> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Michael S <already5chosen@yahoo.com> Newsgroups: comp.lang.c Subject: Re: size_t best practice Date: Sun, 18 Aug 2024 12:36:49 +0300 Organization: A noiseless patient Spider Lines: 43 Message-ID: <20240818123649.00007b53@yahoo.com> References: <VdCcne2MOeshN1z7nZ2dnZfqnPWdnZ2d@brightview.co.uk> MIME-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Injection-Date: Sun, 18 Aug 2024 11:36:12 +0200 (CEST) Injection-Info: dont-email.me; posting-host="909e344cb8e3ca5d8a6a594a2d11c05b"; logging-data="2440532"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/c9vVpwA1l73N7Vt3dClihCUDaOrz8+50=" Cancel-Lock: sha1:78PTMZvFHLnv3Q9yvHcG06H5TvI= X-Newsreader: Claws Mail 3.19.1 (GTK+ 2.24.33; x86_64-w64-mingw32) Bytes: 2544 On Sun, 18 Aug 2024 08:03:08 +0000 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): > > void vec_insert(vec* v, size_t index, void* value) { > if (v->_size == v->_cap) { > vec_grow(v); > } > 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; > } > v->_values[index] = value; > v->_size++; > } > > I've also noticed that quite a few array-related algorithms _assume_ > that indexes are signed, so again I have to put in guards to avoid > subtracting below zero when I use size_t when implementing them. > > So is it considered best practice to use int, long, long long, or > size_t, in situations like these? My personal view is that in order to minimize a surprise factor one should prefer signed array indices and signed loop control variables. I.e. either int or ptrdiff_t. I wouldn't use long or long long. Some systems have ssize_t, but that's not part of standard C. Beyond, I can't imagine a situation where ssize_t is better than ptrdiff_t.