'0' is a character literal.
So when you wrote:
s.push(question[i] - '0');
The fundamental reason why/how question[i] - '0' works is through promotion.
In particular,
both question[i] and '0' will be promoted to int. And the final result that is pushed onto the stack named s will be the result of subtraction of those two promoted int values.
Also note that the C++ Standard (2.3 Character sets) guarantees that:
- ...In both the source and execution basic character sets, the value of
each character after 0 in the above list of decimal digits shall be
one greater than the value of the previous.
For example, say we have:
std::string question = "123";
int a = question[0] - '0'; //the result of question[0] - '0' is guaranteed to be the integer 1
int b = question[1] - '0'; //the result of question[1] - '0' is guaranteed to be the integer 2
int c = question[2] - '0'; //the result of question[2] - '0' is guaranteed to be the integer 3
Lets consider the statement int a = question[0] - '0';:
Here both question[0] and 0 will be promoted to int. And the final result that is used to initialize variable a on the left hand side will be the result of subtraction of those two promoted int values on the right hand side. Moreover, the result is guaranteed to be the integer 1.
Similarly, for statement int b = question[1] - '0';:
Here both question[1] and 0 will be promoted to int. And the final result that is used to initialize variable b on the left hand side will be the result of subtraction of those two promoted int values on the right hand side. Moreover, the result is guaranteed to be the integer 2.
And similarly for variable c.