Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A 'for' loop that appears to be practically infinite

Tags:

c++

I'm debugging some code at the moment, and I've come across this line:

for (std::size_t j = M; j <= M; --j) 

(Written by my boss, who's on holiday.)

It looks really odd to me.

What does it do? To me, it looks like an infinite loop.

like image 244
Michael Bullock Avatar asked Dec 22 '16 07:12

Michael Bullock


People also ask

Can a for loop be infinite?

You can run a for loop infinitely by writing it without any exit condition.

Which loop is used as an infinite loop?

Introduction to Infinite Loop in C. A loop that repeats indefinitely and does not terminate is called an infinite loop. An infinite loop also called as endless loop or indefinite loop.

What is an example of an infinite loop?

What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.

How do you make a for loop infinite?

To make an infinite loop, just use true as your condition. true is always true, so the loop will repeat forever.


1 Answers

std::size_t is guaranteed by the C++ standard to be a unsigned type. And if you decrement an unsigned type from 0, the standard guarantees that the result of doing that is the largest value for that type.

That wrapped-around value is always greater than or equal to M1 so the loop terminates.

So j <= M when applied to an unsigned type is a convenient way of saying "run the loop to zero then stop".

Alternatives such as running j one greater than you want, and even using the slide operator for (std::size_t j = M + 1; j --> 0; ){ exist, which are arguably clearer although require more typing. I guess one disadvantage though (other than the bewildering effect it produces on first inspection) is that it doesn't port well to languages with no unsigned types, such as Java.

Note also that the scheme that your boss has picked "borrows" a possible value from the unsigned set: it so happens in this case that M set to std::numeric_limits<std::size_t>::max() will not have the correct behaviour. In fact, in that case, the loop is infinite. (Is that what you're observing?) You ought to insert a comment to that effect in the code, and possibly even assert on that particular condition.


1 Subject to M not being std::numeric_limits<std::size_t>::max().
like image 132
Bathsheba Avatar answered Sep 29 '22 13:09

Bathsheba