Computer Science Canada [Ada-tut] Control Structures: Case |
Author: | wtd [ Mon Oct 11, 2004 8:52 pm ] | ||||||||
Post subject: | [Ada-tut] Control Structures: Case | ||||||||
Background We can match a value against many others with a long succession of "elsif" clauses, but that gets tiresome, and we end up duplicating code, which, as I've written in the debugging thread, is a very bad thing when it comes to maintaining a program. So instead we use a case structure. Most languages implement this in one way or another. Those familiar with C, C++, or Java may be familiar with the "switch" statement. How Ada85 answers the problem Ada95's "case" construct is functionally the same, but provides some conveniences. Conditions can be ranges of numbers, or several distinct choices, and the "break" statement at the end of each branch is unnecessary. Some code already? Sure, keep your shorts on! ![]() In my tutorial on if and else in Ada, I had a simple example which I'll reimplement here with a case. The old version
The new version
Dissected There isn't much there that shouldn't be pretty straightforward. The "when others" case is essentially equivalent to "else". Using a range Let's say that anything from 7 to 5 is "close enough for government work". Representing this in a C-style "switch" would be quite onerous, but Ada95 makes it easy.
Multiple values, but not a range... If 8 equals 4 or 2, then things are whacky, but since 8 is a multiple of 4 and 2, at least things aren't quite as bad.
Summary Hopefully everything here is fairly well-explained. Questions as always are welcome. |