John D - 1 year ago 62
C Question

# What's the behavior of this code's loop?

``````int main()
{
int i;
int v = 5;
for (i = 0; v; i++)
{
v &= (v - 1);
printf("%d\n", v);
}
return 0;
}
``````

I know it will exit after two iterations, but why?

The loop has a counter (`i`) that starts at zero. It runs the lines within in while it stop condition is not met (i.e., while `v` is `different than`0`).

In each iteration, `v` receives the result of a bitwise `AND` (`&`) between `v` and `v-1`.

Then, the value of `v` is printed at the end of each iteration.

If you add the statement below in just after `for (i = 0; v; i++) {`, you will be able to see what is being done in each iteration:

`printf("i=%d, v=%d, v-1=%d, v & (v-1) = %d\n", i, v, v-1, v & (v - 1));`

Output:

i=0, v=5, v-1=4, v & (v-1) = 4

4

i=1, v=4, v-1=3, v & (v-1) = 0

0

You can try it online here.

In the 1st iteration, `v = 5 & (5 - 1) = 5 & (4) = 4`. Since `v != 0`, the loop continues.

In the 2nd iteration, `v = 4 & (4 - 1) = 4 & (3) = 0`. Since `v == 0`, the loop stops.

As I stated in my comments, in a lower lewel, "there is a comparison being made, probably by a BNZ (branch if not zero) ASM instruction. IF the zero flag is not set, then continue; ELSE, branch. You can find more detailed info here and here."

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download