7/12 In C, what should be the data type for array indices? I usually just
use "int". Thx.
\_ YES! The 'trivial C question troll' is back! I love you, man!
\_ int is fine, but I often find myself using unsigned int, especially
in for loops where I compare unsigned int i against some maximum-
value variable that is also unsigned int.
\_ It's an integer type. a[i] is the same as *(a + i). Can be signed,
can be negative. Why do you care?
\_ I'm just wonder if the K&R spec says anything about it. I don't
have the spec here.
\_ size_t
\_ Are you sure? It's not, say, ptrdiff_t? Isn't a[-1] legal?
\_ You can use ssize_t if you like, I personally prefer
size_t since stuff like a[-1] can often lead to bugs
if you aren't completely sure what a points to.
\_ The original question wasn't what type /should/ be
used; it was what it *is*. Section 6.5.2.1 of the
C99 standard says merely, "integer type" and (as I
said before) that a[i] is identical to *(a + i) (from
which it should be obvious that the index is an integer
type).
\_ To settle this question once and for all, just look at the C
standard? It says the subscript shall be an integral type.
Integral type is defined as char, an unsigned or signed integer
type, or an enumerated type. A signed integer type is signed
char, short int, int, or long int, and unsigned integer type is
the corresponding unsigned type. Clear enough?
\_ You could have just said: The C standard (post URL) says the
index can be an integral type (signed/unsigned short/long
char, int, enum), and negative values are permitted.
\_ There is no URL for the C standard. Or not a legal one,
anyway. There are various draft standards, though.
\_ what about long long?
\_ above is for C90. C99 draft standard has somewhat different
verbiage, but the spirit is the same. basically all integer
types can be subscripts. |