0

I was writing this C program and found out this confusion. what if we use multiple operations on a single variable on a single line. For example,

int arr[5], i = 0;

while(i < 5){
  arr[i] = ++i;
}

and then we print all the elements of the array. here first the increment happens and the the assignment. therefore the elements would be 1, 2, 3, 4, 5. But when I print them, they start out from 0 and then increase upto 4. Can anyone explain what is the logic that is followed here. like why do we get those numbers as an output?

yano
  • 4,827
  • 2
  • 23
  • 35
  • 'what if we use multiple operations on a single variable on a single line' easy - just don't do it. If it looks confusing, it is confusing and you should rewrite it using as many separate lines as required to remove the confusion, (and make debugging much easier and avoid any risk of undefined behaviour). – Martin James Jan 04 '22 at 03:59
  • 4
    It's UB. `i` has unsequenced modification *and* evaluation. If you're using gcc or clang, I suggest you turn on `-Wunsequenced` – WhozCraig Jan 04 '22 at 04:00
  • `arr[i] = ++i;` is dodgy. Use `++i; arr[i] = i;`ro the like – chux - Reinstate Monica Jan 04 '22 at 04:00

0 Answers0