0
Can I use 'while' loop for array and why we use only 'for' loop for array
3 Réponses
+ 4
As a technical side note, All two of them boil down to the same identical assembly instruction.
$Examples$
for (int i = 0; i < 10; ++i)
{
}
ASM Instructions:
mov DWORD PTR [rbp-4], 0 ; as int i = 0
.L3: ; label L3
cmp DWORD PTR [rbp-4], 9 ; as i < 10
jg .L4 ; as goto L4 if the condition is false
add DWORD PTR [rbp-4], 1 ; as ++i
jmp .L3 ; as goto L3 if the condition is true
.L4: ; Label L4
________
int i = 0;
while (i < 10)
{
++i;
}
ASM Instructions:
mov DWORD PTR [rbp-4], 0
.L7:
cmp DWORD PTR [rbp-4], 9
jg .L8
add DWORD PTR [rbp-4], 1
jmp .L7
.L8:
So, the machine doesn't treat these guys differently after compilation. The deal is how do you decide which one is the best fit for the problem.
Live version included do...while loop: https://godbolt.org/g/ZYhfPq
+ 2
you could technically use a while loop to iterate through an array. example:
int i = 0;
while(i < array.Length){...}
but this is much less convenient than a for loop.
+ 1
as hinanawi said, you technically can use a while loop to iterate thru an array, but this is kind of what a for loop is designed for.
when people ask the difference in loops I generally say a while loop runs until a condition is met and a for loop is used to iterate thru something. be it an array, a set number, etc..
So yes, the condition the while loop needs to meet can be the end of the array, but it's better with a for loop