0

I am a beginner in C++, and I saw this function below for adding a word to a trie, and got confused on the line I commented with a question mark. Is the author assigning a char value to an int here? What int value would be assigned?

struct TrieNode
{
    struct TrieNode *children[ALPHABET_SIZE];

    // isEndOfWord is true if the node represents
    // end of a word
    bool isEndOfWord;
};

void insert(struct TrieNode *root, string key)
{
    struct TrieNode *pCrawl = root;

    for (int i = 0; i < key.length(); i++)
    {
        int index = key[i] - 'a';   // ?
        if (!pCrawl->children[index])
            pCrawl->children[index] = getNode();

        pCrawl = pCrawl->children[index];
    }

    // mark last node as leaf
    pCrawl->isEndOfWord = true;
}
user438383
  • 5,716
  • 8
  • 28
  • 43
Bob Jiang
  • 13
  • 3
  • 4
    Chars are small integers. `'a' - 'a'` is 0, `'b' - 'a'` is 1, etc. – HolyBlackCat Nov 03 '21 at 08:35
  • 1
    No. `char` is actually a number. `a` according to ASCII is equal to 97. This is some sort of "trick" to align the indexes pointed by characters to 0. – user3366592 Nov 03 '21 at 08:35
  • 4
    This is an awful piece of C++ code. Don't learn from resources that offer such examples to beginners, prefer [books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) written by real professionals. – Evg Nov 03 '21 at 08:37
  • 1
    Comments that state the obvious and don't mention the non-obvious is a sign that the author has missed the point of comments (or doesn't quite understand their own code). `TrieNode` represents a trie node and `bool isEndOfWord` is true if the node is the end of a word? Really? I could never have guessed. On the other hand, the logic behind that insertion loop is of course obvious to anyone... – molbdnilo Nov 03 '21 at 08:50

1 Answers1

1

char is just a 1-byte number. The computer encodes those numbers to a character using whatever character encoding your computer uses (mostly ASCII).

In ASCII, a has a value of 97, b has a value of 98, ... , z has a value of 122

So:

If key[i] is "a", value = 97 - 97 = 0
If key[i] is "b", value = 98 - 97 = 1
If key[i] is "c", value = 99 - 97 = 2
...
If key[i] is "z", value = 122 - 97 = 25

So, you can see, this is a "trick" to map all the values of key[i] from 0 to 25