Search code examples
c++operation

/= operation in C++


As I understand this code returns the number of digits entered in the function but I don't understand this operation: (number /= 10) != 0 at all..I understand that this line number /= 10 equal to number = number / 10 but why not but why in this function they don't write number / 10 != 0? and what are the differences?

std::size_t numDigits(int number) // function definition.
{                                 // (This function returns
std::size_t digitsSoFar = 1;      // the number of digits
                                  // in its parameter.)
while ((number /= 10) != 0) ++digitsSoFar;
return digitsSoFar;
}

Solution

  • (number /= 10) != 0
    

    This actually has 3 steps. It...

    1. Calculates number / 10
    2. Assigns that value to number
    3. Checks if that value is not equal to 0

    So in answer to your question, "why in this function they don't write number / 10 != 0," let's walk through what that does:

    1. Calculates number / 10
    2. Checks if that value is not equal to 0

    Can you see the difference between the two?

    If you're still not sure why this matters, put an output statement in the while loop that'll show number and digitsSoFar and try to run that function both the way it's written and then with your proposed version.