Reputation: 1276
Given
int x[10];
int y[10];
int n = 10;
Version 1
int i = 0;
while (i < n)
y[i] = x[i++];
Version 2
for (int i = 0; i < n; i++)
y[i] = x[i]
Are the two versions always equivalent? If not, when are they not equivalent?
Upvotes: 1
Views: 106
Reputation: 754570
If we code around the undefined behaviour correctly diagnosed by Greg Hewgill in his answer, then we might end up with code like this:
int x[10] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
int y[10];
int n = 10;
i = 0;
while (i < n)
{
if (i % 3 == 0)
continue;
y[i] = x[i];
i++;
//cont: ;
}
for (i = 0; i < n; i++)
{
if (i % 3 == 0)
continue;
y[i] = x[i];
}
These loops are not equivalent because of the continue
statements — and, indeed, the first is an infinite loop. And the loop bodies could be written without the continue
, but I wanted something simple to illustrate the behaviour of continue
in a while
loop and a for
loop.
The for
loop behaves sanely, not initializing elements y[0]
, y[3]
, y[6]
or y[9]
, but otherwise working perfectly well.
The while
loop looks similar, but the continue;
statement is equivalent to goto cont;
where cont
is the label that is commented out, immediately before the closing brace. Note that it skips the increment of i
, which is why the loop is 'infinite'.
So, the two loops are equivalent if there is no continue
inside.
Note that the related loop:
for (int i = 0; i < n; i++)
{
if (i % 3 == 0)
continue;
y[i] = x[i];
}
is not quite identical to the first for
loop. The variable i
is available outside (after) the loop in the while
loop and the first for
loop; it is not available when the variable is declared in the for
loop itself.
Upvotes: 4
Reputation: 2037
Good question,
take a look here
you can find a nice c to assembler web compiler
I compared the two versions and there are minor assembly differences in the loop implementation.
the functionality seems exactly the same therefor I conclude both samples are always equivalent.
While case:
For case:
Upvotes: 0
Reputation: 994041
This line:
y[i] = x[i++];
is undefined behaviour. You cannot use i
and i++
within the same statement.
Your Version 2, with the i++
inside the for
control statement, is fine.
Upvotes: 7