Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indexing issue with a for loop

I have a for loop where I'm using the slide operator as I'm working with unsigned types. Essentially it boils down to

for (std::size_t i = 6; i --> 0;){
    cout << i;
}

But it outputs the numbers from 5 to 0 inclusive and omits 6. Why?

Thank you very much for looking at this. I'm quite stuck.

like image 652
Fitzwilliam Bennet-Darcy Avatar asked Dec 14 '22 04:12

Fitzwilliam Bennet-Darcy


2 Answers

This is a touchstone for

  1. The fact that this so-called "operator" should be used with caution, if at all.

  2. Changing the state of variables within the conditional check of a for loop ought to be done with extreme caution, if at all.

The largest output is 5 simply because i is decremented as a result of the conditional test which also decrements i. The conditional check is ran before program control enters the for loop body.

You really ought to rewrite the loop. Don't set the initial value of i to 7 as that's a dirty hack. Although --> is often used with while (and to emphasise, it's unlikely to win you many friends in your programming review), I've never seen it used with a for loop before.

like image 95
Bathsheba Avatar answered Dec 16 '22 18:12

Bathsheba


--> is not a slide operator.

It is understood by the compiler as two different operators -- and >.

So your code look like this to the compiler:

for (std::size_t i = 6; (i--) > 0;){
    cout << i;
}

Since the loop condition is checked before entering the loop's body i is decreased before the first execution of the loop's body, hence the produced sequence of numbers is 5 4 3 2 1 0.

For more details see this Stack Overflow question: What is the "-->" operator in C++?

like image 44
Nemanja Trifunovic Avatar answered Dec 16 '22 18:12

Nemanja Trifunovic