maddy
maddy

Reputation: 827

Doubts in a code using do while loop

This is a small piece of code shown below which is using do while loops. I really dont understand the unexpected behaviour i see when i execute this code.This code shown below uses a do while loop condition and from my knowledge a do while loops executes in such a way that if first executes the statement and then checks in the while part if the condition is true or not.But when i execute this code it never comes out of the loop and goes on forever.Can anyone please tell me why is it happening?

           unsigned int A = 5;
           int B = 0;
           main()
          {
               do
               {
                   A = A + 5;
                   B = B - 1;
               }while(B > A);

           printf("hello\n");
          }

Now i never get the "hello" printed.

Thanks in advance Maddy

Upvotes: 1

Views: 393

Answers (5)

Keith Nicholas
Keith Nicholas

Reputation: 44316

prints "hello" for me. takes a while (well, a second or two).

modified to this...

void main()
{
    unsigned int A = 5;
    unsigned int loop = 0;
    int B = 0;
    do
    {
        A = A + 5;
        B = B - 1;
        loop++; 
    }while(B > A);

    printf("hello %d  %d %d\n", B, A, loop);
}

prints out :-

hello -715827882  -715827881 715827882

Upvotes: -1

Jason
Jason

Reputation: 847

You are comparing signed with unsigned. But you will see "hello" eventually. As A and B will both overflow to make B > A false.

Upvotes: 0

Michael Mrozek
Michael Mrozek

Reputation: 175685

As the other answers say, comparing a signed and unsigned value is a bad idea (GCC will warn about it if given the right flags). The reason you're stuck in an "infinite loop" is the signed value B is treated as unsigned for the purpose of the comparison. The first time you get to while(B > A), B is -1 (it started at 0 and was decremented once). When treated as unsigned, it becomes the largest possible integer, so the comparison is true. It remains true for a long time, so the loop appears to never end. Eventually incrementing A and decrementing B would cause them to pass each other and the loop would end, but it will take longer than you anticipated

Upvotes: 4

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76601

Comparing signed and unsigned can lead to confusing behavior. You should make both A and B the same type.

Upvotes: 1

On Freund
On Freund

Reputation: 4436

You're comparing an unsigned int to a negative number. Try turning A into a signed int.

Upvotes: 1

Related Questions