Search code examples
cfor-loopcomma-operator

Newbie: C syntax error when compiling


    for(int a = 0, b = 1; b < n; a++; b++)
    {
        if (compare(values[a], values[b]))
            counter++;
        else
            {
            int x = values[a];
            values[a] = values[b];
            values[b] = x;
            }
    }

I get this error for the first line [ for(int... ] when I try to compile:

helpers.c:68:41: error: expected ')' before ';' token

Why would I need to add another ')'?


Solution

  • for(int a = 0, b = 1; b < n; a++; b++)
                                    ^
                                    |
                                  problem
    

    You need a comma (,) rather than a semicolon (;) at the end of your for-loop where you increment both a and b:

    for(int a = 0, b = 1; b < n; a++, b++)
                                    ^
    

    This is the comma operator.

    These two SO questions might also be helpful: How do I put two increment statements in a C++ 'for' loop? and What is the full "for" loop syntax in C (and others in case they are compatible)?