Search code examples
ccomma-operator

Why this program going to infinite loop?


When i place i<0,5 in the condition part of for loop in following code

#include<stdio.h>
int main()
{
  int i;
  for(i = 0;i<0,5;i++)
    printf("%d\n",i);
  return 0;
}

Solution

  • The answer is 5 is always true.
    Please refer the following code disassembled from yours.
    The condition part is referring just 5.

    move eax, 5 is saving 5 to eax register.
    test eax, eax is comparing between eax and eax.
    It must be always same. So, It's always true.

    009318FA  mov         eax,5
    009318FF  test        eax,eax  
    00931901  je          main+56h (0931916h) 
    

    And It is full code:

            int i;
            for (i = 0; i < 0, 5; i++)
    009318E8  mov         dword ptr [i],0  
    009318EF  jmp         main+3Ah (09318FAh)  
    009318F1  mov         eax,dword ptr [i]  
    009318F4  add         eax,1  
    009318F7  mov         dword ptr [i],eax  
    009318FA  mov         eax,5  
            int i;
            for (i = 0; i < 0, 5; i++)
    009318FF  test        eax,eax  
    00931901  je          main+56h (0931916h)  
                printf("%d\n", i);
    00931903  mov         eax,dword ptr [i]  
    00931906  push        eax  
    00931907  push        offset string "%d\n" (0937B30h)  
    0093190C  call        _printf (093104Bh)  
    00931911  add         esp,8  
    00931914  jmp         main+31h (09318F1h)