for loop statement confusion

What is the for loop statement below mean? Can someone break it down for me? I tried replacing it with for(size_t i = NumBits; i> 0;i--). but it doesn't work. Why's it so?

1
2
for (size_t i = NumBits; i-- > 0;) 
Last edited on
What do you mean by "it doesn't work"?

What are you expecting to happen?

What is the value of NumBits?

but it doesn't work

Everything "works". It just does a different thing.

Lets first recap for and while:
The for loop syntax: for ( initialization; condition; increase ) statement;
1
2
3
4
5
6
7
8
9
10
11
for ( size_t i = NumBits; i > 0; i-- )
{
  // use i
}
// does (almost) same as
size_t i = NumBits;
while ( i > 0 )
{
  // use i
  i--;
}

The increase evaluates after the statement.

Your mystery loop, written as while loop:
1
2
3
4
5
size_t i = NumBits;
while ( i-- > 0 )
{
  // use i
}

The i-- evaluates when the condition is evaluated, before the statement.

What does the condition i-- > 0 do?
For one, we do get a bool value, like we had done:
1
2
bool condition = ( i-- > 0 );
// use condition 

The postfix operator-- has higher priority than the relational >. We could add parentheses to make it clear:
1
2
bool condition = ( (i--) > 0 );
// use condition 

What does the postfix operator-- do? Two things:
1. It modifies the operand, like you had written i = i - 1;
2. It returns a value

Interlude:
How do prefix and postfix decrements differ? They return different value.
1
2
3
4
5
6
7
8
9
// prefix (--i)
i = i - 1;
value = i;
return value;

// postfix (i--)
value = i;
i = i - 1;
return value;

The postfix returns the original value.

Now we can expand our condition:
1
2
3
bool condition = ( i > 0 );
i--;
// use condition 

Put that into while loop:
1
2
3
4
5
6
size_t i = NumBits;
while ( i > 0 )
{
  i--;
  // use i
}

And for:
1
2
3
4
5
for ( size_t i = NumBits; i > 0; )
{
  i--;
  // use i
}

or:
1
2
3
4
for ( size_t i = NumBits; i > 0; i-- )
{
  // use i-1
}

Topic archived. No new replies allowed.