Rexx Programming/How to Rexx/infinite loop

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Infinite loops are sections of code that keep repeating because the programmer doesn't give them a reason to stop. They are common bugs in software that was supposed to stop repeating eventually, but only in a situation that never actually happens.

/* This code was supposed to count to 10 and stop... */
count = 1
do while count <= 10
 say count
end
/* ... but it just keeps saying 1 because the count doesn't change. */

If you actually intend for a loop to keep repeating indefinitely, you can use the FOREVER keyword to signify this.

/* This loop will greet us forever! */
do forever
 say "Hello, world!"
end
/* ... at least until we hurl the computer out the window ... */
/* ... or until we just halt the interpreter manually instead. */

Why would we want that?[edit | edit source]

An infinite loop actually can be useful if there is some important process that needs to continue throughout the lifetime of a program or a part of the program (which will eventually end anyway, for one reason or another). In fact, we usually even embed an exit condition into our so-called infinite loops, so that they aren't really infinite after all. DO FOREVER exists mainly to emphasize that the loop might continue running for a very long time, and that its exit condition isn't necessarily obvious at the beginning of the block.

/* Show the factors of whatever number the user wants. */
/* Keep asking "forever"... but give them an option to stop. */
do forever
 say "What number would you like me to factor for you?"
 say "You can enter zero or a negative number to stop."
 pull number
 /* No need to factor if the user's ready to quit. */
 if number <= 0 then leave
 /* Otherwise let's keep going! */
 say "Here are the factors of" number":"
 do divisor = 1 to number
  if number // divisor = 0 then say divisor
 end
end

DO FOREVER is reasonably popular for loops that would end in the middle, like the one above.

Infinite recursion[edit | edit source]

You can also end up with an infinite loop if a subroutine calls itself over and over. In practice, the interpreter can't always keep track of too many subroutine calls, so recursive subroutines tend to stop when your program overflows the call stack and crashes. Nevertheless, they're theoretically as infinite as DO FOREVER.

/* Shop till you drop! */
 call KEEP_SHOPPING
 exit
KEEP_SHOPPING:
 say "I just keep shopping and shopping..."
 call KEEP_SHOPPING
 return