Deutsch English Français Italiano |
<VdCcne2MOeshN1z7nZ2dnZfqnPWdnZ2d@brightview.co.uk> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!local-2.nntp.ord.giganews.com!Xl.tags.giganews.com!local-1.nntp.ord.giganews.com!nntp.brightview.co.uk!news.brightview.co.uk.POSTED!not-for-mail NNTP-Posting-Date: Sun, 18 Aug 2024 08:03:08 +0000 From: Mark Summerfield <mark@qtrac.eu> Subject: size_t best practice Newsgroups: comp.lang.c MIME-Version: 1.0 User-Agent: Pan/0.149 (Bellevue; 4c157ba) Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Message-ID: <VdCcne2MOeshN1z7nZ2dnZfqnPWdnZ2d@brightview.co.uk> Date: Sun, 18 Aug 2024 08:03:08 +0000 Lines: 32 X-Usenet-Provider: http://www.giganews.com X-Trace: sv3-3Pkrh629gqETGRxnmzRyBkiusGcAXPjY1jNJr2k6Mq4lZgiMy1pIY2F/vsKKqzvmZHQY95LSAdyLtGw!y8GNDO2gfs+Hb2HnEYwuaOfIjUwfFHxrTlgBZohCC3DqGCoZTV6zgociNyJJp9nWvG4HEOgd16WD!ZqFr1R8dQGniBu0zZE3tfBXXQg== X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 Bytes: 2022 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?