sepisoad sepisoad - 1 month ago 10
C Question

C - why putting statement in for loop 'increment' part does not work the first iteration?

this is my code which I expect to see

7, 3, 5, 1, 9

as output but it prints

0, 7, 3, 5, 1

#include <stdio.h>
#define LEN 5

int main(int argc, char const *argv[])
{
int arr[LEN];
int index;
arr[0] = 7;
arr[1] = 3;
arr[2] = 5;
arr[3] = 1;
arr[4] = 9;

int ITM;
for(int IDX = 0; IDX < sizeof(arr) / sizeof(int); ITM = arr[IDX++]){
printf("%d, ", ITM);
}

return 0;
}


what is wrong with this code?

BTW, I know that I can move "ITM = arr[IDX++]" into loop body!

Answer

The behaviour of your program is undefined due to your reading the unitialised variable ITM on the first iteration of the for loop.

ITM is not set to anything until ITM = arr[IDX++] is evaluated, and that doesn't happen until program control gets to the closing } of the for loop.

Writing flashy code like this is occasionally useful, but you need to be aware of the pitfalls.

Comments