Go to the first, previous, next, last section, table of contents.


Using Numbers to Subscript Arrays

An important aspect of arrays to remember is that array subscripts are always strings. If you use a numeric value as a subscript, it will be converted to a string value before it is used for subscripting (see section Conversion of Strings and Numbers).

This means that the value of the CONVFMT can potentially affect how your program accesses elements of an array. For example:

a = b = 12.153
data[a] = 1
CONVFMT = "%2.2f"
if (b in data)
    printf "%s is in data", b
else
    printf "%s is not in data", b

should print `12.15 is not in data'. The first statement gives both a and b the same numeric value. Assigning to data[a] first gives a the string value "12.153" (using the default conversion value of CONVFMT, "%.6g"), and then assigns 1 to data["12.153"]. The program then changes the value of CONVFMT. The test `(b in data)' forces b to be converted to a string, this time "12.15", since the value of CONVFMT only allows two significant digits. This test fails, since "12.15" is a different string from "12.153".

According to the rules for conversions (see section Conversion of Strings and Numbers), integer values are always converted to strings as integers, no matter what the value of CONVFMT may happen to be. So the usual case of

for (i = 1; i <= maxsub; i++)
    do something with array[i]

will work, no matter what the value of CONVFMT.

Like many things in awk, the majority of the time things work as you would expect them to work. But it is useful to have a precise knowledge of the actual rules, since sometimes they can have a subtle effect on your programs.


Go to the first, previous, next, last section, table of contents.