[try Beta version]
Not logged in

 
for loop statement confusion

Jul 19, 2020 at 10:14am
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 Jul 19, 2020 at 10:15am
Jul 19, 2020 at 11:10am
What do you mean by "it doesn't work"?

What are you expecting to happen?

What is the value of NumBits?

Jul 19, 2020 at 11:25am
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.