Understanding the for loop exit condition

I had this question after reading this topic Print int in binary representation using C

In a user comment, they placed this for a loop that assigns either 1 or 0 bit positions to convert from a binary number int to char *.

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

I understand why there is no need to initialize the value. This is the syntax for the for loop I have always known:

for ( variable initialization; condition; variable update )

I do not understand how a “bit” can be an exit condition. Please help me understand how this code works (I tested it and it is valid).

Thank.

+5
source share
4 answers

C "false" . , bits-- 0, "false" .

, :

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

"False", --x 0, "" .

+8

, - 0 . 0 false, true. , , bits 0.

while if ,

if (variable) // or while(variable)

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

,

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

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

bits-- - int ( b, int). for loop, , , , != 0. != 0, - , , .

0

, C - 0 false, true. ( , - a<b int)

, , bits-- 0.

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

So, the loop will exit after the bit is reduced from 0to -1. This means that if at the beginning bits==8(for example), the cycle will be repeated 8 times, when in the first bits will be equal to 7 (because the condition has been checked), and in the last bits will be equal to 0. A good way to loop through an array (since in c is an array variables bitsindexed from 0to bits-1).

0
source

All Articles