What does a[3] = (a[1], a[2]); mean?

Viewed 52

I am wondering what does a[3] = (a[1], a[2]); does in the following code. It returns a[3] = 0. And if I eliminate the parentheses, a[3] = a[1] and a[2] doesn't change its value. Thank you!

#include <stdio.h>

int main(int argc, char ** argv) {
    int a[4] = { 100, 200 }; 
    a[3] = (a[1], a[2]); // What happens here?
    printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);

    return 0;
}
2 Answers

What does a[3] = (a[1], a[2]); mean?

You are assigning a[3] the result from an expression with the comma operator.

Try this example in a debugger and what is happening gets more clear

#include <stdio.h>

int main(){
   int a[10] = { 100, 200 ,-10,-20,-30 }; 
   a[3] = ( a[1]++,a[3]++,a[4]++ );
   printf("%d %d %d %d\n", a[0], a[1], a[2], a[3]);
}

The first part of the expression gets executed, but in your example a[1] is ignored in this example it gets incremented, then a[3] gets assigned the last value in the parenthesis here a[4]

See more in this answer to "How does the Comma Operator work"

a[3] = (a[1], a[2]); // What happens here?

When expressions are separated by commas, the last one is returned.

int a = (1, 2, 3);
// a = 3
Related