szName and pnPtr are pointers and this code is using pointer arithmetic.
Declaring an array creates a sequence of data in memory. Lets say that this sequence begins at memory location 10. The memory is mapped as such:
1 2 3 4 5 6 7
|
szName --> 10 | M
11 | o
12 | l
13 | l
14 | i
15 | e
16 | \0 // null terminator
|
szName + nArraySize
is referring to these memory locations. In this case, that location happens to be 17. Ideally, the code would be
szName + nArraySize - 1
, but that is besides the point.
The for loop begins by assigning szName to pnPtr, and it continues to loop as long as pnPtr is less than 17:
1 2 3 4 5 6 7 8
|
szName --> 10 | M <-- pnPtr
11 | o
12 | l
13 | l
14 | i
15 | e
16 | \0
17 | <-- szName + nArraySize
|
Within the loop, there is a switch case against the deferenced pnPtr. For the first iteration, pnPtr points to 10, which when deferenced, equals the character 'M'. On the second iteration, pnPtr has been incremented, so it now points to 11. The deferenced pnPtr is now 'o', and thus nVowels is incremented.
1 2 3 4 5 6 7 8
|
szName --> 10 | M
11 | o <-- pnPtr
12 | l
13 | l
14 | i
15 | e
16 | \0
17 | <-- szName + nArraySize
|
The loop continues until the value of pnPtr is 17. This isn't exactly ideal because you can see that we have checked to see if the null terminator is a vowel. We know it isn't, so it wasn't necessary to make the loop go that far.
If you want, here is an implementation of strlen() that might be fun to understand:
1 2 3 4 5 6 7 8
|
int myStrlen( const char* str ) // return value should technically be size_t
{
const char* ptr = str;
while ( *ptr++ ); // empty loop
return ptr - str - 1;
}
|