0

How can an array have an index like [0,1,2]?
And why is [0,1,2]=[2]
Code:

int main(){
    int a[]={1,2,3,4,5};
    a[0,1,2]=10;
    for(int i=0;i<5;i++)
        printf("%d ",a[i]);
    return 0;
}

Output:
1 2 10 4 5
  • 4
    If you enabled compiler warnings, you would notice that `0,1,2` is an expression where 0 and 1 are ignored. So frankly it's doing `a[2]=10;` thus setting the value at index `2` to value `10`. And since in C array indexes start at `0`, that is setting the 3rd item. – Cheatah Aug 24 '22 at 07:42

2 Answers2

4

The comma operator (,) evaluates both expressions and returns the second one (see, e.g., this explanation). I.e., 0,1,2 will evaluate to 2, so a[0,1,2]=10 will result in a[2]=10, which explains the output you get.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0
  1. a[0,1,2] will be treated as a[2] aka the other indices are ignored. To test this try: printf("%d ",a[0,1,2]); you will see it prints the value in index 2 only.
  2. To change the values of multiple indices then you either do it manually or iterate over them. For example,

a[0] = 10;

a[1] = 10;

a[2]=10;

OR

for(int i = 0; i < 3; i++)
    a[i]=10;
Wanderer
  • 1,065
  • 5
  • 18
  • 40