0

I was running the code example below, initially trying to print a character array backwards where count represented the number of characters in the array. Everytime I ran the for loop, i was not initalized to count - 1 instead it was initialized to some very large number. But outside the loop, i is properly initalized to 4. I can't explain why this is happening.

size_t count {5};
size_t i {count - 1UL}; // i is initalized to 4

for(size_t i {count - 1}; i >= 0UL; --i) {
    std::cout << i << std::endl;
} // infinite loop, i is initalized to 18446744073709141874
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66

3 Answers3

4

An "unsigned" integer does not have a sign and is always nonnegative. If you do --i on i = 0 then you will get the maximum value of std::size_t.

Do this instead:

// iterates from (count - 1) to 0
for (std::size_t i = count; i--;)

So how does this work? i-- is the postfix decrement operator, which returns the prior value of i. This way, the loop condition is actually comparing count, ..., 1 to zero, while in the loop we get count - 1, ..., 0.

A more generalized version of this idiom is sometimes called the --> operator:

// iterates from (high - 1) to low
for (std::size_t i = high; i-- > low;)
L. F.
  • 19,445
  • 8
  • 48
  • 82
1

std::size_t is unsigned integer type. So values of the type never can be negative.

Rewrite the loop like

std::size_t i {count - 1};

do
{
    std::cout << i << std::endl;
} while ( i-- );
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Firstly, i in the outer scope is unused and shaded, secondly an unsigned integer is always greater than or equal to 0. You could have your compiler detect these if only you turned on your compiler warnings:

<source>:7:38: error: comparison of unsigned expression >= 0 is always true [-Werror=type-limits]

    7 |     for(std::size_t i {count - 1}; i >= 0UL; --i) {

      |                                    ~~^~~~~~

<source>:5:17: error: unused variable 'i' [-Werror=unused-variable]

    5 |     std::size_t i {count - 1UL}; // i is initalized to 4

      |

Solution:

for (unsigned long long i = 4ull; i != -1ull; --i) {
    std::cout << i << '\n';
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93