The C standard (5.1.2.2.1 Program startup) says:
The function called at program startup is named main. [...]
It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ }
or with two parameters [...] :
int main(int argc, char *argv[]) { /* ... */ }
And later says:
The value of argc shall be nonnegative.
argc
be defined as an unsigned int
, argc
supposedly meaning 'argument count'?argc
be used as an index for argv
?So I started wondering if the C standard says something about the type of array's index. Is it signed?
6.5.2.1 Array subscripting:
One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.
It doesn't say anything about its signedness (or I didn't find it). It is pretty common to see codes using negatives array indexes (array[-1]
) but isn't it undefined behavior?
The reason for the int in main() is historical - it's always been that way, since long before the language was standardised. The requirement of an array index is that it is within the bounds of the array (or in some circumstances, one past the end) - anything else is undefined, so the signedness is immaterial.