It's basically an atoi
-type (or atol
-type) function for creating an integral value from a string. Consider the string "123"
.
Before starting, key_num
is set to zero.
- On the first iteration, that's multiplied by 10 to give you 0, then it has the character value
'1'
added and '0'
subtracted, effectively adding 1 to give 1.
- On the second iteration, that's multiplied by 10 to give you 10, then it has the character value
'2'
added and '0'
subtracted, effectively adding 2 to give 12.
- On the third iteration, that's multiplied by 10 to give you 120, then it has the character value
'3'
added and '0'
subtracted, effectively adding 3 to give 123.
Voila! There you have it, 123.
If you change the code to look like:
#include <iostream>
char buf[] = "012345678901234567";
void someFunction(long long *key_num) {
std::cout << *key_num << std::endl;
for (int i = 0; i < 18; i++) {
*key_num = *key_num * 10 + (buf[i] - '0');
std::cout << *key_num << std::endl;
}
}
int main (void) {
long long x = 0;
someFunction (&x);
return 0;
}
then you should see it in action (I had to change your value from the 17-character array you provided in your comment to an 18-character one, otherwise you'd get some problems when you tried to use the character beyond the end; I also had to change to a long long
because my longs weren't big enough):
0
0
1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012
1234567890123
12345678901234
123456789012345
1234567890123456
12345678901234567