Is accessing an array element using a char undefined behaviour?
It is not undefined behavior. It works like another integer type. Yet the numeric value of a char
may surprisingly be negative.
A char
has the same range as signed char
or an unsigned char
. It is implementation defined.
Using c
as an index is fine, if the promoted index plus the pointer results in a valid memory address. Detail: A char
will be promoted to int
, or possible unsigned
.
The following is potentially a problem had c
had a negative value. In OP's case, with ASCII encoding, 'A'
has the value of 65, so it does not have a problem as 0 <= 65 < 3000
. @Joachim Pileborg
char c = 'A';
int a[3000] = { 0 };
printf("%i\n", a[c]); // OK other than a[] not initialize in OP's code.