简体   繁体   中英

Understanding the exit condition of a 'for' loop

I had this question after reading the Stack Overflow quesion Print an int in binary representation using C .

In a user's comment, they posted this for loop, which assigns either a 1 or a 0 to the bit position in order to convert from an int decimal to char * binary.

for(; bits--; u >>= 1)
    str[bits] = u & 1 ? '1' : '0';

I understand why there doesn't need to be an initialized value. This is the syntax for a for loop that I've always known:

for ( variable initialization; condition; variable update )

I don't understand how 'bit--' can be an exit condition. Please help me understand how this code works (I tested it, and it is valid).

In C, a value of zero evaluates to "false" in a boolean context. So when bits-- evaluates to 0 , in the context of the loop it evaluates to "false" and terminates the loop.

If you say, for example:

int x = 1;
if (--x)
{
  printf("True!\n");
}
else
{
  printf("False!\n");
}

It will output "False", because --x evaluates to 0, which is "false" in a boolean context.

All conditions basically boil down to checking whether something is 0 or not. 0 means false , everything else means true . So that loop will break when bits is 0.

You will sometimes see while or if conditions written

if (variable) // or while(variable)

That is just shorthand for

if (variable != 0) // or while (variable != 0)

So

for (; bits--; u >>= 1) 

is short for

for (; bits-- != 0; u >>= 1)

bits-- is assignment expression of type int (since it will return the value of b, which is int). To match the for loop syntax, it gets converted to a boolean expression, which means it is true if bits != 0. In fact, the condition is identical to bits!=0, but by using bits--, it changes the value of bits at the same time, making the code more compact, that's all.

As other said, in C, you can use integers as condition - 0 or false , anything else for true . (Actually, you almost always do it - even an expression like a<b is an int)

So, the loop will end when bits-- will be 0.

When the -- operator comes after the variable, it decreases the variable, and gets the previous value of it. for example, if you have int a=3,b; b=a--; int a=3,b; b=a--; , then b will be 3, and a will be 2.

So, the loop will exit after that bits will been decreased from 0 to -1 . That mean that, if in the beginning, bits==8 (for example), the loop will iterate 8 times, when in the first, bits will be 7 (because the condition had checked), and in the last, bits will be 0. Nice way to loop through an array (Since in c, array of bits variables is been indexed from 0 to bits-1 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM