Help me understand these lines of code

May 21, 2013 at 10:55pm
This is for use with an array, it is being used in a program that counts each occurrence of a letter read in from a .txt file. The question is mostly about character arithmetic and what happens inside of an array. Starting from the static_casting:

1
2
3
4
5
6
int index;

ch = toupper(ch);


index = static_cast<int>(ch)-static_cast<int>('A')


I know that static_cast<>() will change the thing in parens to the type of thing in the <> brackets; I assume that the above arithmetic is a hack that allows us to deal with exclusively letters, but how so?

1
2
if (0<= index && index < 26)
list[index]++


So the above would indicate that the arithmetic gets us into the "letter" range, and then increments the corresponding index by one. Does that mean that the only thing stored in an array is an integer value?

I think I get it mostly, its just the broader concept of the arithmetic that I don't understand, mostly.
Last edited on May 21, 2013 at 10:55pm
May 21, 2013 at 11:30pm
This

index = static_cast<int>(ch)-static_cast<int>('A')


is equivalent to

index = ch - 'A';

There is no any need to use static_cast.

Between latin letter 'A' and letter 'Z' inclusively there are 26 letters. So

'A' - 'A' will give index equal to 0
'B' - 'A' will give index equal to 1
....
'Z' - 'A' will give index 25.

So if ch contains a capital latin letter then ch - 'A' will give some index in the range 0 - 25 that is the logical expression

0<= index && index < 26

will be true.

May 23, 2013 at 2:06pm
Thanks
Topic archived. No new replies allowed.