Indexing problem with for loop

I have a loop forwhere I use the slide operator when I work with unsigned types. Essentially it comes down to

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

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

Thanks for looking at this. I'm completely stuck.

+4
source share
3 answers

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 in a conditional loop test forshould be done with extreme caution, if at all possible.

- 5 , i , i. , for.

. i 7 . --> while (, , ), , for .

+7

--> .

-- >.

, :

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

, i , 5 4 3 2 1 0.

. : "- > " ++?

+4

for

i --> 0

i 5. ,

5

, .

#include <iostream>

int main() 
{
    size_t i = 6;

    do
    {
        std::cout << i;
    } while ( i-- > 0 );

    return 0;
}

6543210

#include <iostream>

int main() 
{
    for ( size_t i = 6; std::cout << i && i != 0; i-- )
    {
        //
    } 

    return 0;
}

, ,

const size_t N = 6;

for ( size_t i = N + 1; i-- > 0; )
//              ^^^^^^^    
{
    std::cout << i;
}

, std::numeric_limits<size_t>::max() 1 , 0.

for .

#include <iostream>

int main() 
{
    const size_t N = 6;

    for ( size_t i = N, j = N; j != 0; j = i-- )
    {
        std::cout << i;
    } 

    return 0;
}

6543210
+1
source

Source: https://habr.com/ru/post/1649935/


All Articles