Eric Sosman
4/30/2011 11:30:00 AM
On 4/30/2011 2:40 AM, Steve Keller wrote:
> 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?
The "overhead" of size_t in this use is probably too small to
measure without effort too large to make sense. In fact, there's
a plausible argument that the "overhead" could even be negative:
Suppose `i' is narrower, and there's extra code to promote it for
every comparison to `ASIZE(a)'. It's not as if you were storing
umpty gazillion size_t values and trying to save space: One variable
and one constant, and that's peanuts.
But if you insist on using a type that might (*might*) be
narrower, unsigned int will placate gcc. The only drawback of
using an unsigned index type (including size_t) is that there's
no way to stop a loop by going negative when stepping backwards,
so you've got to pay close attention to your idioms:
// Doesn't work:
for (unsigned int i = N; --i >= 0; ) { ... }
// Works:
for (unsigned int i = N; i-- > 0; ) { ... }
The latter is sure to arouse suspicion among micro-optimizers,
because half-understood rumors about the relative efficiency of
pre- and post-{in,de}crement operators lurk like shadows in their
brains' dusty and vacant attics. To them -- and to you, with your
worries about the "overhead" of size_t -- I offer Jackson's Laws:
First Law of Program Optimization:
Don't do it.
Second Law of Program Optimization (for experts only):
Don't do it yet.
--
Eric Sosman
esosman@ieee-dot-org.invalid