A variable created inside a loop changes value during iterations in C

Our product has code similar to the following. For me, the output is "0 1 2 3". But the output of a similar code is "1 1 1 1".

for(i = 0 ;i < 5;i++){
    int j;
    if(i)
        printf("%d ",j);
    j = i;
}

I understand that j is pushed onto the stack only once during the entire period of the 'for' loop, and the same value is used during iterations. Also, if I move ad j outside the loop, I get the expected result. What am I missing here?

PS - When I run the same code on my personal machine, I get the expected result. But in production it is different.

+4
source share
2 answers

-, , C11, Β§6.2.4, ( )

, static , [...]

,

, , , , , . ( , , .) , . .

, j. .

    int j;   //not initialized
    if(i)
        printf("%d ",j);  //this one here

j, . undefined .

C11, Β§6.7.9

,

, UB, Β§J.2

, .

UB, .

OTOH, j , . , , j.

, , i, 0, if false, printf() , j . , , printf(), j , .

+7

, , for :

i = 0;
LoopStart:
if(!(i<5)){ goto LoopEnd;}

{
    int j;
    if(i)
        printf("%d ",j);
    j = i;
}

i++;
goto LoopStart;
LoopEnd:

, , : , , 5 . , , uninitialized j printf.

/. , - , j , , j, , , j, , .

0

Source: https://habr.com/ru/post/1628432/


All Articles