Why does my while >0 go past 0 into negative numbers? in C

Onceler

Golden Member
Feb 28, 2008
1,262
0
71
Code:
#include <stdio.h>

int main ()
{

    FILE * pfile;
    unsigned long long bytesremaining =0;
    unsigned long long remain = 0;
    char name[150] = "";
    printf("enter the file name and path\n");
    gets(name);

    pfile = fopen (name,"rb");

    if (pfile==NULL)
        perror ("Error opening file");
    else
    {
        fseeko64 (pfile, 0, SEEK_END);
        remain = ftello64 (pfile);
        bytesremaining=remain;
        printf(" bytes left =%I64d\n",bytesremaining);
        fclose (pfile);
        printf ("\nFile:\n%s\ncontains %I64d bytes:\n", name, remain);
        while (bytesremaining >0)
        {
            printf("bytes remaining = %I64d\n" , bytesremaining);
            bytesremaining =bytesremaining-8;

        }
        break;
    }
    return 0;
}
thanks
 

Jaydip

Diamond Member
Mar 29, 2010
3,691
21
81
Code:
#include <stdio.h>

int main ()
{

    FILE * pfile;
    unsigned long long bytesremaining =0;
    unsigned long long remain = 0;
    char name[150] = &quot;&quot;;
    printf(&quot;enter the file name and path\n&quot;);
    gets(name);

    pfile = fopen (name,&quot;rb&quot;);

    if (pfile==NULL)
        perror (&quot;Error opening file&quot;);
    else
    {
        fseeko64 (pfile, 0, SEEK_END);
        remain = ftello64 (pfile);
        bytesremaining=remain;
        printf(&quot; bytes left =%I64d\n&quot;,bytesremaining);
        fclose (pfile);
        printf (&quot;\nFile:\n%s\ncontains %I64d bytes:\n&quot;, name, remain);
        while (bytesremaining >0)
        {
            printf(&quot;bytes remaining = %I64d\n&quot; , bytesremaining);
            bytesremaining =bytesremaining-8;

        }
        break;
    }
    return 0;
}
thanks

Make bytesremaining signed.If a unsigned variableis assigned negative value in "C" it is converted to a positive integer.Just think it's very simple.
 

Tweak155

Lifer
Sep 23, 2003
11,449
264
126
Geez C is looking more like Greek every time I come back to it. Unsigned long long? The insanity!
 

exdeath

Lifer
Jan 29, 2004
13,679
10
81
You are subtracting more than is remaining and its wrapping to a positive unsigned int. What is the initial value of bytesremaining going into the loop? Probably not a multiple of 8. Sounds like you are trying to work in bytes and qwords at the same time, not sure why you are subtracting 8.

Step through it in a debugger and see for yourself.

Though I really don't see what that loop is accomplishing in the first place...
 
Last edited:

douglasb

Diamond Member
Apr 11, 2005
3,157
0
76
As others have said, it's because you are using an unsigned type and your original bytesremaining value is not a multiple of 8. So suppose that its value is 3 and you subtract 8. Since it's unsigned, the sign bit gets ignored and it gets evaluated as 5 (instead of -5). 5 is greater than 0, so your loop continues when it should have stopped.