0

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;
}
Raviteja
  • 367
  • 2
  • 11

2 Answers2

2

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) 
yaho cho
  • 1,779
  • 1
  • 7
  • 19
  • Can I get some more explanation as I am not familiar with that machine level code. When i executed it , it going to infinite loop why that is happening and what operation is going there?? – Raviteja Jul 27 '19 at 17:18
  • 1
    @RaviTeja `,` means multiple operations in same line code. You wrote 2 operations as the condition part of `if statement`. In this case, Compiler applies one of operations. So, I converted it to machine level code to make sure which one is applied. From `i < 0, 5`, `5` is applied because C compiler reads codes by left to right. And, I added more explanation in my answer about machine code. – yaho cho Jul 27 '19 at 23:57
0

If you want the loop to stops after 5 iterations you have to write

for(i = 0;i<5;i++)
   printf("%d\n",i);

As suggested you by melpomene, the comma operation is explained here

Tony Barletta
  • 375
  • 1
  • 8