I would not use that code as a learning example. There are so many errors in it that I wasn't even able to properly compile it.
What is the function of RANGE
?
When you compile your code a special program called a preprocessor runs beforehand. The preprocessor essentially replaces a lot of things. It usually does this based on statements called preprocessor directives and they begin with the "#" symbol. In this case, #define RANGE 255
is telling the preprocessor to replace every occurence of "RANGE" in the code with "255". For example, the line int count[RANGE + 1], i
becomes int count[255 + 1], i
.
Why do we have to specifically define the RANGE
to be 255?
To be completely honest I'm not sure why the code decided to use 255 for RANGE
. I've tested the code and it works just fine with RANGE
equal to 114 and it doesn't work with numbers. If you increase the length of the input string "geeksforgeeks" to something much larger then RANGE
won't be sufficiently large enough.
How does the code convert the characters to numeric equivalents to be stored in the count array?
The char
data type is actually an integer. Every character we use (A to Z, 0 to 9, punctuation, etc) all has a corresponding number. For example the code below will print out the number which corresponds to a
which is "97".
#include <iostream>
int main()
{
char name[] = "abc";
int a = name[0];
std::cout << a;
return 0;
}
The line ++count[arr[i]];
simply accesses element i
in the array arr
and appends it to the count
integer array which it can do because char
is an integer. Once we have it in the count
integer array it is treated like a normal integer and when we print it out in the console it shows us a number rather than a character.