Search code examples
c++algorithmsortingbubble-sort

bubble sort algorithm for loop statement warning


I saw a piece of bubble sort code and initially I thought the code is wrong. But after compile and run, it surprised me that it actually works. I want to know how come second statement in the first for loop is not a condition but an assignment. In addition, how come this code will not go into infinitely loop?

PS: It will generate an warning: "suggest parentheses around assignment used as truth value [-Wparentheses]" complaining about the first for loop. Surprisingly it's not an error.

#include <iostream>

void bubblesort(int A[], int n)
{
    for (bool sorted = false; sorted = !sorted; n--)
    {
        for (int i = 1; i < n; ++i)
        {
            if (A[i-1] > A[i])
            {
                int tmp = 0;
                tmp = A[i];
                A[i] = A[i-1];
                A[i-1] = tmp;
                sorted = false;
            }
        }
    }
}

int main()
{
    int a[5] = {1,4,5,2,3};

    bubblesort(a, 5);

    for (unsigned int i = 0; i < 5; ++i)
    {
        std::cout << a[i] << std::endl;
    }

    return 0;
}

Solution

  • The result of an assignment is the left operand, so the condition

    sorted = !sorted
    

    is using sorted as the condition after it's assigned a new value. The warning is there to give you a notice that using assignment as condition is sometimes not what you expected. You can use

    (sorted = !sorted) == true
    

    to silence the warning.