Fitzwilliam Bennet-Darcy Fitzwilliam Bennet-Darcy - 1 year ago 60
C++ Question

Indexing issue with a for loop

I have a

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download