views:

82

answers:

2

A long time ago, I thought I saw a proposal to add an else clause to for or while loops in C or C++... or something like that. I don't remember how it was supposed to work -- did the else clause run if the loop exited normally but not via a break statement?

Anyway, this is tough to search for, so I thought maybe I could get some CW answers here for various languages.

What languages support adding an else clause to something other than an if statement? What is the meaning of that clause? One language per answer please.

+7  A: 

Python.

Example use:

for element in container:
  if element == target:
    break
else:
  # this will not be executed if the loop is quit with break.
  raise ElementNotFoundError()

From the Python docs:

it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

KennyTM
Hey, sweet! Thanks for teaching me something :)
Thomas
+2  A: 

There is so-called "Dijkstra's Loop" (also called "Dijkstra's Guarded Loop"). It was defined in The Guarded Command Language (GCL). You can find some information about it syntax and semantic in the above Wikipedia article at the section 6 Repetition: do.

Nowadays I actually know one programming language which supports this control struture directly. It is Oberon-07 (PDF, 70 KB). And it supports "Dijkstra's Loop" in thу form of while statement. Take a look at section 9.6. While statements in the above PDF.

WHILE m > n DO m := m – n 
ELSIF n > m DO n := n – m 
END
kemiisto
Interesting... seems more like an `ELSEWHILE` than an `ELSIF`. Definitely different semantics from the Python use of while-else. Thanks for sharing!
Dan