Search | | Contact Us | Resource Center Login | Home|

What is the output of the following program?

           x     ,a1
           y     ,a1
           x = 12
           y = 21
           writes(1,  %string(%add(x,y)))
    function add, ^val
    in req mismatch   a      ,n
    in req mismatch   b      ,n
          freturn a + b

a. "33"
b. "3"
c. "1221"
d. "21"
e. This does not compile

Correct answer: (b)


This program assigns two numeric values to two variables and then passes them to the function "add," which adds them together and returns the result. The program writes that result to its output.

Because 12 plus 21 yields 33, the obvious answer seems to be (a)—until we look more closely. That would be the correct answer if the variables x and y were declared as integers, but they're declared as alphanumeric instead. Whereas an i1 could contain each of the values 12 and 21, an a1 cannot. When assigning a number to an alphanumeric variable, the number is converted to its character representation and is right-aligned within the field. Since these numbers have two digits, the resulting two characters won't fit in an a1, so their higher order digits are silently truncated, resulting in 2 and 1, respectively.

When we add alphanumeric values, the result is their concatenation. So, you might think that (d) would be the correct answer. But hold on, we have yet another transformation occurring. These variables are passed to the function "add," which defines its parameters as type mismatch n.
That means that an alphanumeric value will be treated as if it were decimal (type d).  Thus, the addition operation inside the function adds the two numbers 1 and 2 to yield 3, making (b) the correct answer.

If we had omitted the word "mismatch" from the parameter declarations, the compiler would not have allowed this code (e). That's probably the better way to write the function, to catch such errors as using an alphanumeric when you meant an integer. At least it would force the caller to convert the value to numeric explicitly if that operation were desired, by using a function like %INTEGER or a decimal cast.

More information about News and Events

Contact Synergex to learn more about  News and Events