+ 2

What is the difference between the two loop below? (In terme of execution time )

for (int x = 1; x < 10; x++) { // some code } AND x=1 while(x <10) { // some code x++; }

22nd Jul 2017, 8:31 PM
Lahmadi Mohamed
Lahmadi Mohamed - avatar
2 Answers
+ 7
There is no difference, they both generate the exact same assembly code ( no optimization ): 0000000000000000 <main>: 0: sub rsp,0x38 4: call 9 <main+0x9> 9: mov DWORD PTR [rsp+0x2c],0x1 10: 11: cmp DWORD PTR [rsp+0x2c],0x9 16: jg 1f <main+0x1f> 18: add DWORD PTR [rsp+0x2c],0x1 1d: jmp 11 <main+0x11> 1f: mov eax,0x0 24: add rsp,0x38 28: ret
22nd Jul 2017, 8:44 PM
Dennis
Dennis - avatar
+ 8
the variable x can be used outside 'while loop' but for 'for loop' no (x declared in the for statement) ;)
23rd Jul 2017, 3:41 AM
Chokri ZAGROUBA
Chokri ZAGROUBA - avatar