Is arr[i] = i; legal?

143 Views Asked by At

I want to initialize a value of all array members to their index.

int main()
{
    int i;
    int arr[10];

    for (i = 0; i <= 9; i++)
        arr[i] = i;
}

Should I consider the sequence point in this case?
Is arr[i] = i legal and portable?

2

There are 2 best solutions below

0
HolyBlackCat On BEST ANSWER

You need to consider sequence points if you modify something more than once in one place, or if you both read and modify something in one place.

You're not doing any of that, so your code is fine.

0
AudioBubble On

There is no restriction its just assigning a value to the array index

If you just want an array of 0123456789 its fine

Although its only one line its a good practice to use {}

for (i = 0; i <= 9; i++)
{
   arr[i] = i;
}