Sujet : Re: size_t best practice
De : Bonita.Montero (at) *nospam* gmail.com (Bonita Montero)
Groupes : comp.lang.cDate : 27. Aug 2024, 17:11:42
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vaktrt$321u8$1@raubtier-asyl.eternal-september.org>
References : 1
User-Agent : Mozilla Thunderbird
Am 18.08.2024 um 10:03 schrieb Mark Summerfield:
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?
I adhere to the semantics some of the C++-containers which use a size_t
as an index. So I use a size_t for indices. And if I need to iterate
down to and including zero I use a ptrdiff_t. On all systems with a
flat address space size_t and ptrdiff_t are as wide as a pointer.
And if I need the largest integer that fits into a general purpose
register I'm also using a size_t, thereby beging more efficient than
using a uin64_6 on a 32 bit platform.