Search code examples
c++functionvariable-assignmentunary-operator

Unary operations in C++


I came across a programming question of which I knew only a part of the answer.

int f( char *p )
{
int n = 0 ;
while ( *p != 0 )
n = 10*n + *p++ - '0' ;
return n ;
}

This is what I think the program is doing. p is a pointer and the while loop is DE-refrencing the values of the pointer until it equals 0. However I don't understand the n assignment line, what is '0' doing? I am assuming the value of p is initially negative, that is the only way it will reach 0 after the increment.


Solution

  • You are confusing the number zero (none, nothing) with the character 0 (a circle, possibly with a slash through it). Notice that zero is in tick marks, so it's the character "0", not the number zero.

    '0' - '0' = 0
    '1' - '0' = 1
    '2' - '0' = 2
    ...

    So by subtracting the character zero from a digit, you get the number that corresponds to that digit.

    So, say you have this sequence of digits: '4', '2', '1'. How do you get the number four-hundred and twenty-one from that? You turn the '4' into four. Then you multiply by ten. Now you have fourty. Convert the '2' into two and add it. Now you have fourty-two. Multiply by ten. Convert the '1' into one, and add, now you have four hundred and twenty one.

    That's how you convert a sequence of digits into a number.