Search code examples
arrayscindexingcomma-operator

Multiple arguments to the index of the array in c


I went through the following code :

#include <stdio.h>
#define N   10000000
int main() {
    static int rot[N], dd[N], qu[N];
    int a, t, i, j, p, head, cnt;
    scanf("%d%d", &a, &t);
    for (i = 0, p = 1; i < N; i++) {
        while (p * 10 <= i)
            p *= 10;
        rot[i] = i % 10 == 0 ? -1 : (i % 10) * p + i / 10;
    }
    for (i = 0; i < N; i++) 
        dd[i] = N;
    head = cnt = 0;
    dd[1] = 0, qu[head + cnt++] = 1;
    while (cnt) {
        int d;
        i = qu[cnt--, head++], d = dd[i] + 1;
        if (i == t) {
            printf("%d\n", dd[i]);
            return 0;
        }
        if ((long long) i * a < N) {
            j = i * a;
            if (dd[j] > d)
                dd[j] = d, qu[head + cnt++] = j;
        }
        if (rot[i] != -1) {
            j = rot[i];
            if (dd[j] > d)
                dd[j] = d, qu[head + cnt++] = j;
        }
    }
    printf("-1\n");
    return 0;
}

As one can see, qu is a static int array, i want to know what "i = qu[cnt--, head++]," line does, how are we passing two arguments to the index of array.


Solution

  • Within the subscript operator there is used an expression with the comma operator.

    qu[cnt--, head++],
    

    The result of the expression is the value of the second operand.

    From the C Standard (6.5.17 Comma operator)

    2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

    In my opinion it is a bad style of programming that only confuses readers of the code because it is unclear whether there is a typo and instead of the comma there should be for example the operator + something like
    qu[cnt-- + head++] similar to qu[head + cnt++]. Maybe there is indeed a typo.