Search code examples
carraysindexingcomma-operator

Wrong array indexing does not cause error


Consider the following program:

#include <stdio.h>
int main(void)
{
    int a[] = {1, 2, 3};

    for (size_t i = 0; i < 3; i++)
        printf ("%i\n", a[0, i]);

    return 0;
}

Obviously, the one-dimensional array a is accessed like a two-dimensional array in for example Python. However, this code does compile with a unused-value warning. I expected it to produce an error, because I always thought this for is of multiindexing is simply wrong in C (See K&R page 112). To my surprise, the above code indeed prints out the array elements.

If you change a[0, i] on line six to a[i, 0], the first array element is printed three times. If you you use a[i, 1] the second element is printed three times.

How is a syntactically wrong multi-index on a one-dimensional array translated to pointer arithmatic and what value of the result of a[i, 0] is unused?

And, yes, I know how to multi-index in C.


Solution

  • The comma here, is the comma operator. It's not a multi-indexing (which ideally would have been of the form [0][i] or [i][0]).

    Quoting C11, chapter §6.5.17 (emphasis mine)

    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.

    So, in your case,

    a[0, i]
    

    is the same as

    a[i]
    

    and

    a[i, 0]
    

    is same as

    a[0]