Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!gegeweb.org!de-l.enfer-du-nord.net!feeder1.enfer-du-nord.net!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Dr Nick <3-nospam@temporary-address.org.uk> Newsgroups: comp.lang.c Subject: Re: int vs. unsigned int vs. size_t Date: Sun, 01 May 2011 14:16:34 +0100 Lines: 37 Message-ID: <87tydev9vx.fsf@temporary-address.org.uk> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Trace: individual.net hJmtKUSRLQ+a0Yjcru8SBQR2CqanHk6Iy5LJUxH0rbPVypsgnU Cancel-Lock: sha1:3P+biLMuNBBJamJ8+7xDXy/IbJY= sha1:BEzOYNmUvIWoMvTxlapOSNvroG4= User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Xref: x330-a1.tempe.blueboxinc.net comp.lang.c:3102 Steve Keller writes: > This is a style question. To iterate through an array I often use > code similar to the following: > > #define ASIZE(a) (sizeof(a) / sizeof((a)[0]) > int a[] = { ... }; > > void foo(void) > { > int i; > for (i = 0; i < ASIZE(a); i++) > /* do something with a[i]. */ > } > > With all warnings enabled, gcc will warn about a comparison between > signed and unsigned integer types, because sizeof() yields a size_t > which is unsigned. To eliminate that warning I could use unsigned int > or size_t for the variable i. But IMO int feels most natural and > size_t might have unwanted overhead, if it is a large integer type and > I know that the array size will be very small (i.e. less than INT_MAX > elements). > > So, what type for i do you prefer in cases like this? I hit another issue with this a couple of days ago. If you /do/ use an unsigned type for 'i', and the array has no items in it, and you use GCC with -W you get: warning: comparison is always false due to limited range of data type With a cast of the result of the sizeof division, and a normal signed int, you get no warnings. I have to confess that this confuses me. -- Online waterways route planner | http://canalplan.eu Plan trips, see photos, check facilities | http://canalplan.org.uk