Could someone please explain what this does in the code above?

for (; num; num /= base) {
            // Note: abs() is done on each digit instead of the whole num 
            // to preserve the full range of int
            result.insert(result.begin(), digits[abs(num % base)]);
        }

Recommended Answers

All 3 Replies

I think

for (; num; num /= base) {

could be written

for (; num != 0; num /= base) {

It was using the idea of "anything non zero evaluates to true (or "continue the loop") while when it is zero the loop should stop.

So basically the loop is dividing 'num' by 'base' over and over until the division yields zero.

This line:

result.insert(result.begin(), digits[abs(num % base)]);

Just puts the number digits[abs(num % base)] on the end of the string.

David

Oh that makes sense now!! thx so much I appreciate it.

Please mark this thread as solved since WaltP separated it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.