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.
This is a touchstone for
The fact that this so-called "operator" should be used with caution, if at all.
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.
-->
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++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With