Search code examples
cdo-whileinsertion-sort

! operator in do while loop


I'm just doing a tutorial on insertion sorting in C, and I'm struggling to understand the way the ! operator is used as the condition for a do while loop.

The condition is just while (!done) but I don't understand how it knows what is not supposed to be equal to the variable done. Something like while (done==0) would make more sense to me.

I'm only just starting to code so sorry if the answer is really obvious! I tried googling it but I found it hard to express the problem...

The code is as follows:

void insertionSortArray (int arr[])
{
    for(int i = 1; i < SIZE; i++)
    {
        int value = arr[i];
        int j = i -1;
        int done = 0;
        do
        {
            if (arr[j]>value)
            {
                arr [j+1] = arr[j];
                j - -;
                if (j<0)
                done = 1;
            }

            else
                done = 1;

        } while (!done);

        arr [j+1] = value;
    }
}

Thanks!!


Solution

  • They're exactly the same thing. !done and done == 0 are interchangeable. The thing about C is: it didn't have a "true" boolean type for a long time. Booleans were only introduced in C99.

    All zero values are considered false, other values are true. that's why !done is true, for as long as done == 0 (done is 0 -> false, !false -> true). ! is the logical NOT operator, as always, and does what it does: negates whatever comes after. Therefore done = 0 => done is false, !done -> the opposite of false, being true.

    If you find done == 0 easier to read, then by all means write it like that. Although, it is more common to see the shorter version.

    False/true checks that are Very common:

    type *foo = malloc(123 * sizeof *foo);
    if (!foo)
        exit(1); // failed to alloc memory
    
    void my_function(int *ptr, size_t size)
    {
        if (!ptr)
            return; // a NULL pointer was passed
        // ...
    }
    

    TL;DR

    Because both statements are interchangeable, write what you find makes the most sense. Perhaps reading both statements aloud (although it may seem silly) will make you change your mind:

    while done equals zero
    //vs
    while not done
    

    Which of the two sentences makes most sense now?