Euphoria - Constants



Constants are also variables that are assigned an initial value that can never change in the program’s life. Euphoria allows to define constants using constant keyword as follows −

constant MAX = 100
constant Upper = MAX - 10, Lower = 5
constant name_list = {"Fred", "George", "Larry"}

The result of any expression can be assigned to a constant, even one involving calls to previously defined functions, but once the assignment is made, the value of the constant variable is "locked in".

Constants may not be declared inside a subroutine. The scope of a constant that does not have a scope modifier, starts at the declaration and ends and the end of the file it is declared in.

Examples

#!/home/euphoria-4.0b2/bin/eui

constant MAX = 100
constant Upper = MAX - 10, Lower = 5

printf(1, "Value of MAX %d\n", MAX )
printf(1, "Value of Upper %d\n", Upper )
printf(1, "Value of Lower %d\n", Lower )

MAX = MAX + 1
printf(1, "Value of MAX %d\n", MAX )

This produces the following error −

./test.ex:10
<0110>:: may not change the value of a constant
MAX = MAX + 1
   ^

Press Enter

If you delete last two lines from the example, then it produces the following result −

Value of MAX 100
Value of Upper 90
Value of Lower 5

The enums

An enumerated value is a special type of constant where the first value defaults to the number 1 and each item after that is incremented by 1. Enums can only take numeric values.

Enums may not be declared inside a subroutine. The scope of an enum that does not have a scope modifier, starts at the declaration and ends and the end of the file it is declared in.

Examples

#!/home/euphoria-4.0b2/bin/eui

enum ONE, TWO, THREE, FOUR

printf(1, "Value of ONE %d\n", ONE )
printf(1, "Value of TWO %d\n", TWO )
printf(1, "Value of THREE %d\n", THREE )
printf(1, "Value of FOUR %d\n", FOUR )

This will produce following result −

Value of ONE 1
Value of TWO 2
Value of THREE 3
Value of FOUR 4

You can change the value of any one item by assigning it a numeric value. Subsequent values are always the previous value plus one, unless they too are assigned a default value.

#!/home/euphoria-4.0b2/bin/eui

enum ONE, TWO, THREE, ABC=10, XYZ

printf(1, "Value of ONE %d\n", ONE )
printf(1, "Value of TWO %d\n", TWO )
printf(1, "Value of THREE %d\n", THREE )
printf(1, "Value of ABC %d\n", ABC )
printf(1, "Value of XYZ %d\n", XYZ )

This produce the following result −

Value of ONE 1
Value of TWO 2
Value of THREE 3
Value of ABC 10
Value of XYZ 11

Sequences use integer indices, but with enum you may write code like this −

enum X, Y
sequence point = { 0,0 }

point[X] = 3
point[Y] = 4
Advertisements