What is the best syntax to use a char to index into an array.
It depends.
///////////////////////////////////
For example
data['a'] = 1;
data['b'] = 1;
///////////////////////////////////
gcc is complaining about this syntax, so i am using static
cast on the character literal. Is there a better way to do
this?
It depends on the context.
First, this is a warning; you can turn it off, or ignore it. In
fact, it is a legitimate warning unless you've taken adequate
precautions; a char may have negative values. (But then, so may
an int. Logically, g++ shouldn't warn unless the size of the
array is such that not all entries can be reached by a char, and
not in the case of a character literal, in any case. But in
fact, it does always warn, unless you turn that warning off.)
The first case is when the array will normally be indexed by an
int, and you're just using character literals during
initialization; if the only indexation by a char is with a
character literal, you can simply ignore the warning. (Note
that this is a more or less usual idiom: you read the array with
a return value of istream::get(), for example, after having
checked for EOF.)
If you really do want to index with arbitrary characters, there
are three solutions:
1. If portability isn't a large concern, you can just compile
with -funsigned-char. This should really be the default,
but there are historical reasons which mean that it isn't.
Other compilers also have such an option. (It's /J for
VC++, I think.) If you're certain that you'll never have to
port to a compiler without this option, you can just use it,
and be assured that plain char is unsigned.
In this case, you'll still have to turn off the warning from
g++. (IMHO, the warning, as it is currently implemented, is
stupid. If they want to warn, it would be more reasonable
to warn when the type of the index cannot encompass all of
the possible index values, and only if the value is not a
constant.)
2. Otherwise, you can cast to unsigned_char anytime you use a
char as an index.
3. Or, you can rearrange the array, and use character -
CHAR_MIN as an index.
In the latter two cases, I'd wrap the array in a class which
took care of the "correction" of the index.