When shadowing i inside the for loop, the following code
#include <stdio.h>
int main()
{
for (int i = 1; i < 5; i++) {
printf("%d", i);
int i = i;
printf("%d ", i);
}
}
outputs:
10 20 30 40
From my understanding of shadowing, there should've been a new i created with the value equal to the previous i. This means the output I expected would've been:
11 22 33 44
Furthermore, the code seems to store the new i value if you increment it.
#include <stdio.h>
int main()
{
for (int i = 1; i < 5; i++) {
printf("%d", i);
int i = i + 2;
printf("%d ", i);
}
}
this outputs:
12 24 36 48
Seemingly, i is not being redeclared every iteration - it works like a variable that was initially 0 and then was incremented every iteration.
What's actually happening here? How do you predict the behaviour?
int i = i;actually assignsito itself (not theiof the loop`) and accessing it is UB.int i = ihere does the RHS refer to the for loop iterator or is it already shadowing there?iis in scope within its own initialization, the RHS must be the "new"iwhich shadows the outer one.i. It is already in scope, othertwise a bareint i = i;wouldn't be legal.uninitialized local variable 'i' usedfor the lineint i = i; andint i = i + 2;.