-1

So I have a digit counter:

`int count = 1;
 int value = 3879418911067976105;
 while (value != 0)
 {
     value /= 10;
     count++;
 }`

And it produces an infinite loop. When I change count to 0, the maximum value count reaches is 9. I'm fairly new to C, can anyone explain why this is happening?

iRicky01
  • 31
  • 5

3 Answers3

6

First of all, your value variable is too large and it's overflowing. You can check the largest value it can have by running this code:

#include <limits.h>

int main() {
    printf("INTMAX = %d\n", INT_MAX);
    return 0;
}

(More on this topic here).
On a typical 32-bit machine this will output INTMAX = 2147483647. That would mean that your number is actually silently converted to 287551913.

Apart from this, I don't see how changing the initial value of count could affect the termination of the loop. I would say your code is doing something else, which you are not showing, and that is responsible for that. The code here runs fine on ideone.com:

#include <stdio.h>
#include <limits.h>

int main(void) {
    int count = 0;
    int value = 3879418911067976105;

    printf("INTMAX = %d\n", INT_MAX);
    while (value != 0)
    {
        printf("value = %d\n", value);
        value /= 10;
        count++;
    }
    printf("count = %d\n", count);
    return 0;
}
Community
  • 1
  • 1
  • Thank you! I guess I don't know the various data types all that well. This helped me fix up this and the rest of my project as well. – iRicky01 Sep 23 '15 at 01:14
4

Your code has several things wrong with it. First of all, that number is too long for an int. You need to use long long int. Second of all, you need to initialize count = 0 or you will be off by one. Code below works for me:

int count = 0;
long long int value = 3879418911067976105;
while (value != 0)
{
    value /= 10;
    printf("Value = %lld\n", value);
    count++;
}
printf("Count = %d\n", count);

And produces the following output (I added printfs so it's easier to see what's happening):

Value = 387941891106797610 
Value = 38794189110679761 
Value = 3879418911067976 
Value = 387941891106797 
Value = 38794189110679 
Value = 3879418911067 
Value = 387941891106 
Value = 38794189110 
Value = 3879418911 
Value = 387941891 
Value = 38794189 
Value = 3879418 
Value = 387941 
Value = 38794
Value = 3879 
Value = 387 
Value = 38 
Value = 3 
Value = 0 
Count = 19
rost0031
  • 1,894
  • 12
  • 21
1

The problem is that you are causing an overflow on the int variable value. Hence, C makes an implicit conversion on the value using only the part of the bit sequence that canbe stored into a variable of type int.

When I executed you code, the value that initially ws stored was 287551913. Hence, 10 (or 9, if you start at 0) is the correct answer.

The solution proposed, changing the value to LL works because there will be no overflow, but you still may have the same issue with larger numbers.

I hope it helps.

rlinden
  • 2,053
  • 1
  • 12
  • 13