2

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;
}
zmag
  • 7,825
  • 12
  • 32
  • 42
rodan
  • 57
  • 3
  • `a[3]` does not change its value, it is given `0` from the initialization – Simson Oct 18 '19 at 03:40
  • I haven't seen any expression like this before...like apparently a[3] is not a tuple or a set, so what's the function of the parentheses here? Thank you! – rodan Oct 18 '19 at 03:44
  • `a[3]` is assigned the last in the parenthesis the fist values are unused is is 0 because `a[2]` is 0 – Simson Oct 18 '19 at 03:50

2 Answers2

0

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"

Simson
  • 3,373
  • 2
  • 24
  • 38
0

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
zmag
  • 7,825
  • 12
  • 32
  • 42