why does this while loop work?

The below function confuses me. Basically, since unsigned integers use a two's complement system, we cannot take the inverse of n before processing it, should n be negative. Because the largest negative number does not have absolute value representation. Thus, we use abs here after processing n % 10 while n is still negative. But how does that while loop work? Why doesn't it loop forever? If n is -133, reducing it by a factor of 10 with each iteration, it will start spitting out -1 infinitely. Am I missing something?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void itoa(int n, char s[]) {

    int i, sign;

    sign = n;

    

    i = 0;

    do {

        s[i++] = abs(n % 10) + '0';

    } while ( n /= 10 );

    if (sign < 0)

        s[i++] = '-';

    

    s[i] = '\0';

    reverse(s);

}
If n is -133, reducing it by a factor of 10 with each iteration, it will start spitting out -1 infinitely. Am I missing something?
-1 / 10 == 0 — Intel ariphmetics.
Also -6 % 10 == -6. That is why there is abs() here
However negative number division and modulus is implementation defined so I would not use it outside of platform specific routines.

Because the largest negative number does not have absolute value representation.
Implementation defined actually. Signed integers do not have to use 2s complement.
Last edited on
Topic archived. No new replies allowed.