C ++, should array indices be int?

In C ++, the const,, array arrcontains 100 numbers from 0 to 80.

If I select numbers in arras chars, they will be implicitly converted intevery time they are used as indices on double pointers, i.e. doublepointer[arr[i]]?

+4
source share
4 answers

Yes, they will be converted to type int. According to the C ++ standard, "the index operator [] is interpreted in such a way that E1 [E2] is identical to * ((E1) + (E2))." And if the additive operator is used, then "Normal arithmetic conversions are performed for the operands of arithmetic or an enumeration type." This means that objects of type char will be converted to objects of type int when they are used in expressions as indices in the index operator.

Note that the char type may behave as an unsigned char or as a signed char depending on the compiler options that you select or which are set by default.

As for types that can be used as indices in an indexed statement, they must be either unplanned enumerations or some integer types.

+3

- , .

STL, . std:: map std::vector operator [], (, map -s) . , - at.

+1

, , int . , . Char , , , . , , , . , . , int

0

, " ". ; , - .

( , "" - .)

int. , , . arr[i], ; unsigned int long long, .

, , char , , . " " , , , int, int unsigned int. , , int.

If your implementation has a simple signed char, and if the value turns out to be negative, then it will be raised to a negative value int, which is probably not what you want. In your particular case, you say that the values ​​are in the range of 0 to 80, all of which are in the range of positive values ​​of the type char. But in case your requirements change later, you better define your array with the element type unsigned char.

0
source

All Articles