Lolo_Fsho
Lolo_Fsho

Reputation: 61

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).

Upvotes: 6

Views: 2679

Answers (4)

asaelr
asaelr

Reputation: 5456

As others said, in C, you can use integers as a condition - 0 or false, and 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--;, 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 means 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. It is a nice way to loop through an array (Since in C, an array of bits variables is being indexed from 0 to bits-1).

Upvotes: 0

Diego
Diego

Reputation: 18359

bits-- is an 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.

Upvotes: 0

Charles Salvia
Charles Salvia

Reputation: 53299

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.

Upvotes: 9

Seth Carnegie
Seth Carnegie

Reputation: 75130

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)

Upvotes: 1

Related Questions