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
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;
}
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.
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.a[0] = 10;
a[1] = 10;
a[2]=10;
OR
for(int i = 0; i < 3; i++)
a[i]=10;