Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 545
Lolo_Fsho Avatar asked Feb 09 '12 00:02

Lolo_Fsho


2 Answers

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.

like image 188
Charles Salvia Avatar answered Sep 27 '22 22:09

Charles Salvia


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)
like image 27
Seth Carnegie Avatar answered Sep 27 '22 23:09

Seth Carnegie