Yet another kind of constant definition is the set definition.
This useful for defining flag sets, i.e., a number of options each of which can be on or off.
The definition is like a simple enumeration, but using the SET
keyword and this time the values start at one and increase as powers of two (so the next value is two, the next is four, the next eight, and so on).
Therefore, the following definitions are equivalent:
SET ENGLISH, FRENCH, GERMAN, JAPANESE, RUSSIAN CONST ENGLISH=1, FRENCH=2, GERMAN=4, JAPANESE=8, RUSSIAN=16
However, the significance of the values it is best shown by using binary constants:
CONST ENGLISH=%00001, FRENCH=%00010, GERMAN=%00100, JAPANESE=%01000, RUSSIAN=%10000
If a person speaks just English then we can use the constant ENGLISH
.
If they also spoke Japanese then to represent this with a single value we'd normally need a new constant (something like ENG_JAP
OR
the ENGLISH
and JAPANESE
values together to get a new value, %01001
, and this represents a set containing both ENGLISH
and JAPANESE
.
On the other hand, to find out if someone speaks French we would AND
the value for the languages they know with %00010
(or the constant FRENCH
).
(As you might have guessed, AND
and OR
are really bit-wise operators, not simply logical operators.
See 10.4.3 Bitwise AND
and OR
.)
Consider this program fragment:
speak:=GERMAN OR ENGLISH OR RUSSIAN /* Speak any of these */ IF speak AND JAPANESE WriteF('Can speak in Japanese\n') ELSE WriteF('Unable to speak in Japanese\n') ENDIF IF speak AND (GERMAN OR FRENCH) WriteF('Can speak in German or French\n') ELSE WriteF('Unable to speak in German or French\n') ENDIF
The assignment sets speak
to show that the person can speak in German, English or Russian.
The first IF
block tests whether the person can speak in Japanese, and the second tests whether they can speak in German or French.
When using sets be careful you don't get tempted to add values instead of OR
-ing them.
Adding two different constants from the same set is the same as OR
-ing them, but adding the same set constant to itself isn't.
This is not the only time addition doesn't give the same answer, but it's the most obvious.
If you to stick to using OR
you won't have a problem.
Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.