CALC
Evaluates a simple mathematical expression.
Type
Dialog Language function
Format
CALC(expression varname)- expression
- A string containing the expression to be evaluated. Only integers
and the operators listed below in ascending precedence are valid:
- +
- Addition
- -
- Subtraction
- *
- Multiplication
- /
- Integer division (result)
- %
- Modulo division (remainder)
- -
- Unary minus (same symbol as subtraction)
Parentheses can be used to group terms to alter the order of evaluation.
- varname
- The name of a variable to be updated with the result of the calculation. If the calculation cannot be performed, the variable is not updated.
Return Codes
- 0
- expression was evaluated, and the result is in varname.
- 4
-
expression or varname was omitted or there is a syntax error in expression. Ensure that the CALC arguments are not null and that expression contains a valid mathematical formula.
- 8
- Numeric overflow. Numbers and the results of calculations must be between -2,147,483,648 and 2,147,483,647, inclusive. It may be possible to reorder the calculations in your expression to eliminate an intermediate calculation overflow.
- 12
- Stack overflow. The expression is too complicated to be evaluated. For example, it contains too many levels of parentheses. Reduce the number of parenthetical expressions.
Usage Notes®
- Only numbers are allowed. Any expression must be numeric. However,
you can use variables in the string to be calculated:
set A 1 set B 8 set rc (calc('&A+&B' Result))The Dialog Manager evaluates the contents of the variables A and B before it builds the string that is passed to CALC. The result is '1+8', which can be processed correctly.
- Enclose expression in single quotation marks to prevent tokenization and truncation to 8 characters.
- CALC can handle a maximum negative value of -2,147,483,648. However,
you cannot specify the value directly in expression because
CALC treats the leading minus sign as a unary operator against the
positive value 2,147,483,648, which is too large. To use the maximum
negative value in a calculation, code it as follows:
(-2147483647 - 1) - Division or modulo by 0 results in RC=8, numeric overflow.
Example
The following example builds a simple
calculator:
)option level(1) popup
)declare
Exp scope(local) * expression string
Msg scope(local) * results message
RC scope(local) * return code from CALC
Result scope(local) * evaluation result
)init
set Exp 0 /* init exp string */
)prologue
set rc (calc('&Exp' Result))
if &RC = 0 set Msg 'Result is &Result'
else if &RC = 4 set Msg 'Syntax error in expression'
else if &RC = 8 set Msg 'Numeric overflow'
else set Msg 'Stack overflow'
)body
# SIMPLE CALCULATOR
#
#Enter expression:_Exp #
#
#&Msg
)epilogue
if &Syskey = ENTER reshow /* do it again */