In c++ chars are almost the same thing as integers and they are stored as integers. So when you are performing hash[magazine[i]]++;
what really happens is that the magazine[3]
(which is the NULL character) will be promoted to an int (Source: cpp reference: Implicit Conversions, the equivalent of which is 0 based on the cpp reference: ASCII codes.
Thus, the statement hash[3] = 0
is true
.
That said, the below code which is similar to the code used in the example
string x = hash[magazine[3]]++; //first x is assigned with the value of hash[magazine[3]], then hash[magazine[3]] is incremented.
cout << "output: " << x << "\n";
will produce output: 0
.
That happens because the hash[0]
is assigned with the value of hash[magazine[3]]
before the increment operator.Equivalently, the increment (++ operator) will be evaluated after the rest of the expression is -- after the assignment has been done.
If you want to avoid this behavior, you can do the below:
string x = ++hash[magazine[3]]; //first hash[magazine[0]] is incremented, then it is assigned to x.
cout << "output: " << x << "\n";
which will produce output: 1
.
However, hash[magazine[i]]++
is inside a loop. This means that after the loop concludes, the expression has already been evaluated and the hash array contains the new values, thus, hash[0]
will be equal to 1
.
Cheers,