Merge from vendor branch GCC:
[dragonfly.git] / contrib / bc / doc / bc.texi
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename bc.info
4 @settitle bc Command Manual
5 @c %**end of header
6
7 @c This file has the new style title page commands.
8 @c Run `makeinfo' rather than `texinfo-format-buffer'.
9
10 @smallbook
11
12 @c tex
13 @c \overfullrule=0pt
14 @c end tex
15
16 @titlepage
17 @title @command{bc}
18 @subtitle an arbitrary precision calculator language
19 @subtitle version 1.06
20
21 @author Philip A. Nelson
22 @page
23
24 This manual documents @command{bc}, an arbitrary precision calculator language.
25
26 This manual is part of GNU @command{bc}.@*
27 @sp4
28 Copyright (C) 1991, 1992, 1993, 1994, 1997 Free Software Foundation, Inc.
29 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
30
31 Permission is granted to make and distribute verbatim copies of
32 this manual provided the copyright notice and this permission notice
33 are preserved on all copies.
34
35 @iftex
36 Permission is granted to process this file through TeX and print the
37 results, provided the printed document carries copying permission
38 notice identical to this one except for the removal of this paragraph
39 (this paragraph not being relevant to the printed manual).
40 @end iftex
41
42 Permission is granted to copy and distribute modified versions of this
43 manual under the conditions for verbatim copying, provided that the entire
44 resulting derived work is distributed under the terms of a permission
45 notice identical to this one.
46
47 Permission is granted to copy and distribute translations of this manual
48 into another language, under the above conditions for modified versions,
49 except that this permission notice may be stated in a translation approved
50 by the Foundation.
51
52 You may contact the author by:
53 e-mail: @email{phil@@cs.wwu.edu}@*
54 us-mail: Philip A. Nelson@*
55 Computer Science Department, 9062@*
56 Western Washington University@*
57 Bellingham, WA 98226-9062
58
59 @end titlepage
60
61 @node Top, Introduction, (dir), (dir)
62
63 @menu
64 * Introduction::
65 * Basic Elements::
66 * Expressions::
67 * Statements::
68 * Functions::
69 * Examples::
70 * Readline and Libedit Options::
71 * GNU @command{bc} and Other Implementations::
72 * Limits::
73 * Environment Variables::
74 @end menu
75
76 @node Introduction, Basic Elements, Top, Top
77 @chapter Introduction
78 @menu
79 * Description::
80 * Command Line Options::
81 @end menu
82
83 @node Description, Command Line Options, Introduction, Introduction
84 @section Description
85
86 @command{bc} [ -hlwsqv ] [long-options] [ @var{ file ...} ]
87
88 @command{bc} is a language that supports arbitrary precision numbers
89 with interactive execution of statements.  There are some similarities
90 in the syntax to the C programming language. 
91 A standard math library is available by command line option.
92 If requested, the math library is defined before processing any files.
93 @command{bc} starts by processing code from all the files listed
94 on the command line in the order listed.  After all files have been
95 processed, @command{bc} reads from the standard input.  All code is
96 executed as it is read.  (If a file contains a command to halt the
97 processor, @command{bc} will never read from the standard input.)
98
99 This version of @command{bc} contains several extensions beyond
100 traditional @command{bc} implementations and the POSIX draft standard.
101 Command line options can cause these extensions to print a warning or to
102 be rejected.  This document describes the language accepted by this
103 processor.  Extensions will be identified as such.
104
105 The author would like to thank Steve Sommars
106 (@email{Steve.Sommars@@att.com}) for his extensive help in testing the
107 implementation.  Many great suggestions were given.  This is a much
108 better product due to his involvement.
109
110 Email bug reports to @email{bug-bc@@gnu.org}.  Be sure to include
111 the word ``bc'' somewhere in the ``Subject:'' field.
112
113 @node Command Line Options, Numbers, Description, Introduction
114 @section Command Line Options
115
116 @command{bc} takes the following options from the command line:
117 @table @code
118
119 @item -h, --help
120 Print the usage and exit.
121
122 @item -l, --mathlib
123 Define the standard math library.
124
125 @item -w, --warn
126 Give warnings for extensions to POSIX @command{bc}.
127
128 @item -s, --standard
129 Process exactly the POSIX @command{bc} language.
130
131 @item -q, --quiet
132 Do not print the normal GNU @command{bc} welcome.
133
134 @item -v, --version 
135 Print the version number and copyright and quit.
136
137 @end table
138
139
140 @node Basic Elements, Expressions, Introduction, Top
141 @chapter Basic Elements
142 @menu
143 * Numbers::
144 * Variables::
145 * Comments::
146 @end menu
147
148 @node Numbers, Variables, Command Line Options, Basic Elements
149 @section Numbers
150
151 The most basic element in @command{bc} is the number.  Numbers are
152 arbitrary precision numbers.  This precision is both in the integer part
153 and the fractional part.  All numbers are represented internally in
154 decimal and all computation is done in decimal.  (This version truncates
155 results from divide and multiply operations.)  There are two attributes
156 of numbers, the length and the scale.  The length is the total number of
157 significant decimal digits in a number and the scale is the total number
158 of decimal digits after the decimal point.  For example, .000001 has a
159 length of 6 and scale of 6, while 1935.000 has a length of 7 and a scale
160 of 3.
161
162 @node Variables, Comments, Numbers, Basic Elements
163 @section Variables
164
165 Numbers are stored in two types of variables, simple variables and
166 arrays.  Both simple variables and array variables are named.  Names
167 begin with a letter followed by any number of letters, digits and
168 underscores.  All letters must be lower case.  (Full alphanumeric
169 names are an extension. In POSIX @command{bc} all names are a single
170 lower case letter.)  The type of variable is clear by the context
171 because all array variable names will be followed by brackets ( [ ] ).
172
173 There are four special variables, @var{scale}, @var{ibase}, @var{obase}, and
174 @var{last}.  @var{scale} defines how some operations use digits after the
175 decimal point.  The default value of @var{scale} is 0. @var{ibase}
176 and @var{obase} define the conversion base for input and output
177 numbers.  The default for both input and output is base 10.
178 @var{last} (an extension) is a variable that has the value of the last
179 printed number.  These will be discussed in further detail where
180 appropriate.  All of these variables may have values assigned to them
181 as well as used in expressions.
182
183 @node Comments, , Variables, Basic Elements
184 @section Comments
185
186 Comments in @command{bc} start with the characters @code{/*} and end with
187 the characters @code{*/}.  Comments may start anywhere and appear as a
188 single space in the input.  (This causes comments to delimit other
189 input items.  For example, a comment can not be found in the middle of
190 a variable name.)  Comments include any newlines (end of line) between
191 the start and the end of the comment.
192
193 To support the use of scripts for @command{bc}, a single line comment has been
194 added as an extension.  A single line comment starts at a @code{#}
195 character and continues to the next end of the line.  The end of line
196 character is not part of the comment and is processed normally.
197
198 @node Expressions, Statements, Basic Elements, Top
199 @chapter Expressions
200
201 @menu 
202 * About Expressions and Special Variables::
203 * Basic Expressions::
204 * Relational Expressions::
205 * Boolean Expressions::
206 * Precedence::
207 * Special Expressions::
208 @end menu
209
210 @node About Expressions and Special Variables, Basic Expressions, Expressions, Expressions
211 @section About Expressions and Special Variables
212
213 The numbers are manipulated by expressions and statements.  Since
214 the language was designed to be interactive, statements and expressions
215 are executed as soon as possible.  There is no main program.  Instead,
216 code is executed as it is encountered.  (Functions, discussed in
217 detail later, are defined when encountered.)
218
219 A simple expression is just a constant. @command{bc} converts constants
220 into internal decimal numbers using the current input base, specified by
221 the variable @var{ibase}. (There is an exception in functions.)  The
222 legal values of @var{ibase} are 2 through 16.  Assigning a value outside
223 this range to @var{ibase} will result in a value of 2 or 16.  Input
224 numbers may contain the characters 0-9 and A-F. (Note: They must be
225 capitals.  Lower case letters are variable names.)  Single digit numbers
226 always have the value of the digit regardless of the value of
227 @var{ibase}. (i.e. A = 10.)  For multi-digit numbers, @command{bc}
228 changes all input digits greater or equal to @var{ibase} to the value of
229 @var{ibase}-1.  This makes the number @code{FFF} always be the largest
230 3 digit number of the input base.
231
232 Full expressions are similar to many other high level languages.
233 Since there is only one kind of number, there are no rules for mixing
234 types.  Instead, there are rules on the scale of expressions.  Every
235 expression has a scale.  This is derived from the scale of original
236 numbers, the operation performed and in many cases, the value of the
237 variable @var{scale}. Legal values of the variable @var{scale} are
238 0 to the maximum number representable by a C integer.
239
240 @node Basic Expressions, Relational Expressions, About Expressions and Special Variables, Expressions
241 @section Basic Expressions
242
243 In the following descriptions of legal expressions, "expr" refers to a
244 complete expression and "@var{var}" refers to a simple or an array variable.
245 A simple variable is just a 
246
247 @var{name}
248
249 and an array variable is specified as 
250
251 @var{name}[@var{expr}] 
252
253 Unless specifically mentioned the scale of the result is the maximum
254 scale of the expressions involved.
255
256 @table @code
257 @item - expr
258 The result is the negation of the expression.
259
260 @item ++ @var{var}
261 The variable is incremented by one and the new value is the result of
262 the expression.
263
264 @item -- @var{var}
265 The variable
266 is decremented by one and the new value is the result of the
267 expression.
268
269 @item @var{var} ++
270  The result of the expression is the value of
271 the variable and then the variable is incremented by one.
272
273 @item @var{var} --
274 The result of the expression is the value of the variable and then
275 the variable is decremented by one.
276
277 @item expr + expr
278 The result of the expression is the sum of the two expressions.
279
280 @item expr - expr
281 The result of the expression is the difference of the two expressions.
282
283 @item expr * expr
284 The result of the expression is the product of the two expressions.
285
286 @item expr / expr
287 The result of the expression is the quotient of the two expressions.
288 The scale of the result is the value of the variable @code{scale}
289
290 @item expr % expr
291 The result of the expression is the "remainder" and it is computed in the
292 following way.  To compute a%b, first a/b is computed to @var{scale}
293 digits.  That result is used to compute a-(a/b)*b to the scale of the
294 maximum of @var{scale}+scale(b) and scale(a).  If @var{scale} is set
295 to zero and both expressions are integers this expression is the
296 integer remainder function.
297
298 @item expr ^ expr
299 The result of the expression is the value of the first raised to the
300 second. The second expression must be an integer.  (If the second
301 expression is not an integer, a warning is generated and the
302 expression is truncated to get an integer value.)  The scale of the
303 result is @var{scale} if the exponent is negative.  If the exponent
304 is positive the scale of the result is the minimum of the scale of the
305 first expression times the value of the exponent and the maximum of
306 @var{scale} and the scale of the first expression.  (e.g. scale(a^b)
307 = min(scale(a)*b, max(@var{scale}, scale(a))).)  It should be noted
308 that expr^0 will always return the value of 1.
309
310 @item ( expr )
311 This alters the standard precedence to force the evaluation of the
312 expression.
313
314 @item @var{var} = expr
315 The variable is assigned the value of the expression.
316
317 @item @var{var} <op>= expr
318 This is equivalent to "@var{var} = @var{var} <op> expr" with the
319 exception that the "@var{var}" part is evaluated only once.  This can
320 make a difference if "@var{var}" is an array.
321 @end table
322
323 @node Relational Expressions, Boolean Expressions, Basic Expressions, Expressions
324 @section Relational Expressions
325
326 Relational expressions are a special kind of expression that always
327 evaluate to 0 or 1, 0 if the relation is false and 1 if the relation is
328 true.  These may appear in any legal expression.  (POSIX @command{bc}
329 requires that relational expressions are used only in @code{if},
330 @code{while}, and @code{for} statements and that only one relational
331 test may be done in them.)  The relational operators are
332
333 @table @code
334 @item expr1 < expr2
335 The result is 1 if expr1 is strictly less than expr2.
336
337 @item expr1 <= expr2
338 The result is 1 if expr1 is less than or equal to expr2.
339
340 @item expr1 > expr2
341 The result is 1 if expr1 is strictly greater than expr2.
342
343 @item expr1 >= expr2
344 The result is 1 if expr1 is greater than or equal to expr2.
345
346 @item expr1 == expr2
347 The result is 1 if expr1 is equal to expr2.
348
349 @item expr1 != expr2
350 The result is 1 if expr1 is not equal to expr2.
351 @end table
352
353 @node Boolean Expressions, Precedence, Relational Expressions, Expressions
354 @section Boolean Expressions
355
356 Boolean operations are also legal.  (POSIX @command{bc} does NOT have
357 boolean operations). The result of all boolean operations are 0 and 1
358 (for false and true) as in relational expressions.  The boolean
359 operators are:
360
361 @table @code
362 @item !expr
363 The result is 1 if expr is 0.
364
365 @item expr && expr
366 The result is 1 if both expressions are non-zero.
367
368 @item expr || expr
369 The result is 1 if either expression is non-zero.
370 @end table
371
372 @node Precedence, Special Expressions, Boolean Expressions, Expressions
373 @section Precedence
374
375 The expression precedence is as follows: (lowest to highest)
376
377 @example
378 || operator, left associative
379 && operator, left associative
380 ! operator, nonassociative
381 Relational operators, left associative
382 Assignment operator, right associative
383 + and - operators, left associative
384 *, / and % operators, left associative
385 ^ operator, right associative
386 unary - operator, nonassociative
387 ++ and -- operators, nonassociative
388 @end example
389
390 This precedence was chosen so that POSIX compliant @command{bc} programs
391 will run correctly. This will cause the use of the relational and
392 logical operators to have some unusual behavior when used with
393 assignment expressions.  Consider the expression:
394
395 @example
396 a = 3 < 5
397 @end example
398
399 Most C programmers would assume this would assign the result of "3 <
400 5" (the value 1) to the variable "a".  What this does in @command{bc} is
401 assign the value 3 to the variable "a" and then compare 3 to 5.  It is
402 best to use parentheses when using relational and logical operators
403 with the assignment operators.
404
405 @node Special Expressions, , Precedence, Expressions
406 @section Special Expressions
407
408 There are a few more special expressions that are provided in
409 @command{bc}.  These have to do with user-defined functions and standard
410 functions.  They all appear as
411 "@var{name}@code{(}@var{parameters}@code{)}".  @xref{Functions}, for
412 user-defined functions.  The standard functions are:
413
414 @table @code
415 @item length ( expression )
416 The value of the length function is the number of significant digits in the
417 expression.
418
419 @item read ( )
420 The @code{read} function (an extension) will read a number from the
421 standard input, regardless of where the function occurs.  Beware, this
422 can cause problems with the mixing of data and program in the standard
423 input.  The best use for this function is in a previously written
424 program that needs input from the user, but never allows program code to
425 be input from the user.  The value of the @code{read} function is the
426 number read from the standard input using the current value of the
427 variable @var{ibase} for the conversion base.
428
429 @item scale ( expression )
430 The value of the @code{scale} function is the number of digits after the
431 decimal point in the expression.
432
433 @item sqrt ( expression )
434 The value of the @code{sqrt} function is the square root of the
435 expression.  If the expression is negative, a run time error is
436 generated.
437 @end table
438
439 @node Statements, Functions, Expressions, Top
440 @chapter Statements
441
442 @menu
443 * Pseudo Statements::
444 @end menu
445
446 Statements (as in most algebraic languages) provide the sequencing of
447 expression evaluation.  In @command{bc} statements are executed "as soon
448 as possible."  Execution happens when a newline in encountered and there
449 is one or more complete statements.  Due to this immediate execution,
450 newlines are very important in @command{bc}. In fact, both a semicolon
451 and a newline are used as statement separators.  An improperly placed
452 newline will cause a syntax error.  Because newlines are statement
453 separators, it is possible to hide a newline by using the backslash
454 character.  The sequence "\<nl>", where <nl> is the newline appears to
455 @command{bc} as whitespace instead of a newline.  A statement list is a
456 series of statements separated by semicolons and newlines.  The
457 following is a list of @command{bc} statements and what they do: (Things
458 enclosed in brackets ( [ ] ) are optional parts of the statement.)
459
460 @table @var
461 @item expression
462 This statement does one of two things.  If the expression starts with
463 "<variable> <assignment> ...", it is considered to be an assignment
464 statement.  If the expression is not an assignment statement, the
465 expression is evaluated and printed to the output.  After the number is
466 printed, a newline is printed.  For example, "a=1" is an assignment
467 statement and "(a=1)" is an expression that has an embedded assignment.
468 All numbers that are printed are printed in the base specified by the
469 variable @var{obase}. The legal values for @var{obase} are 2 through
470 BC_BASE_MAX (@pxref{Environment Variables}).  For bases 2 through 16,
471 the usual method of writing numbers is used.  For bases greater than 16,
472 @command{bc} uses a multi-character digit method of printing the numbers
473 where each higher base digit is printed as a base 10 number.  The
474 multi-character digits are separated by spaces.  Each digit contains the
475 number of characters required to represent the base ten value of
476 "@var{obase} -1".  Since numbers are of arbitrary precision, some
477 numbers may not be printable on a single output line.  These long
478 numbers will be split across lines using the "\" as the last character
479 on a line.  The maximum number of characters printed per line is 70.
480 Due to the interactive nature of @command{bc}, printing a number causes
481 the side effect of assigning the printed value to the special variable
482 @var{last}. This allows the user to recover the last value printed
483 without having to retype the expression that printed the number.
484 Assigning to @var{last} is legal and will overwrite the last printed
485 value with the assigned value.  The newly assigned value will remain
486 until the next number is printed or another value is assigned to
487 @var{last}.  (Some installations may allow the use of a single period
488 (.) which is not part of a number as a short hand notation for for
489 @var{last}.)
490
491 @item string
492 The string is printed to the output.  Strings start with a double quote
493 character and contain all characters until the next double quote character.
494 All characters are taken literally, including any newline.  No newline
495 character is printed after the string.
496
497 @item @code{print} @var{list}
498 The @code{print} statement (an extension) provides another method of
499 output.  The @var{list} is a list of strings and expressions separated by
500 commas.  Each string or expression is printed in the order of the list.
501 No terminating newline is printed.  Expressions are evaluated and their
502 value is printed and assigned to the variable @code{last}. Strings in
503 the print statement are printed to the output and may contain special
504 characters.  Special characters start with the backslash character (\e).
505 The special characters recognized by @command{bc} are "a" (alert or
506 bell), "b" (backspace), "f" (form feed), "n" (newline), "r" (carriage
507 return), "q" (double quote), "t" (tab), and "\e" (backslash).  Any other
508 character following the backslash will be ignored.
509
510 @item @{ statement_list @}
511 This is the compound statement.  It allows multiple statements to be
512 grouped together for execution.
513
514 @item @code{if} ( expression ) statement1 [@code{else} statement2]
515 The if statement evaluates the expression and executes statement1 or
516 statement2 depending on the value of the expression.  If the expression
517 is non-zero, statement1 is executed.  If statement2 is present and
518 the value of the expression is 0, then statement2 is executed.  (The
519 @code{else} clause is an extension.)
520
521 @item @code{while} ( expression ) statement
522 The while statement will execute the statement while the expression
523 is non-zero.  It evaluates the expression before each execution of
524 the statement.   Termination of the loop is caused by a zero
525 expression value or the execution of a @code{break} statement.
526
527 @item @code{for} ( [expression1] ; [expression2] ; [expression3] ) statement
528 The @code{for} statement controls repeated execution of the statement.
529 @var{Expression1} is evaluated before the loop.  @var{Expression2} is
530 evaluated before each execution of the statement.  If it is non-zero,
531 the statement is evaluated.  If it is zero, the loop is terminated.
532 After each execution of the statement, @var{expression3} is evaluated
533 before the reevaluation of expression2.  If @var{expression1} or
534 @var{expression3} are missing, nothing is evaluated at the point they
535 would be evaluated.  If @var{expression2} is missing, it is the same as
536 substituting the value 1 for @var{expression2}.  (The optional
537 expressions are an extension. POSIX @command{bc} requires all three
538 expressions.)  The following is equivalent code for the @code{for}
539 statement:
540
541 @example
542 expression1;
543 while (expression2) @{
544    statement;
545    expression3;
546 @}
547 @end example
548
549 @item @code{break}
550 This statement causes a forced exit of the most recent enclosing @code{while}
551 statement or @code{for} statement.
552
553 @item @code{continue}
554 The @code{continue} statement (an extension)  causes the most recent enclosing
555 @code{for} statement to start the next iteration.
556
557 @item @code{halt}
558 The @code{halt} statement (an extension) is an executed statement that
559 causes the @command{bc} processor to quit only when it is executed.  For
560 example, "if (0 == 1) halt" will not cause @command{bc} to terminate
561 because the @code{halt} is not executed.
562
563 @item @code{return}
564 Return the value 0 from a function.  (@xref{Functions}.)
565
566 @item @code{return} ( expression )
567 Return the value of the expression from a function.  (@xref{Functions}.)
568 As an extension, the parenthesis are not required.
569 @end table
570
571 @node Pseudo Statements, , Statements, Statements
572 @section Pseudo Statements
573
574 These statements are not statements in the traditional sense.  They are
575 not executed statements.  Their function is performed at "compile" time.
576
577 @table @code
578 @item limits
579 Print the local limits enforced by the local version of @command{bc}.  This
580 is an extension.
581
582 @item quit
583 When the @code{quit} statement is read, the @command{bc} processor
584 is terminated, regardless of where the @code{quit} statement is found.  For
585 example, "if (0 == 1) quit" will cause @command{bc} to terminate.
586
587 @item warranty
588 Print a longer warranty notice.  This is an extension.
589 @end table
590
591 @node Functions, Examples, Statements, Top
592 @chapter Functions
593
594 @menu
595 * Math Library Functions::
596 @end menu
597
598 Functions provide a method of defining a computation that can be
599 executed later.  Functions in @command{bc} always compute a value and
600 return it to the caller.  Function definitions are "dynamic" in the
601 sense that a function is undefined until a definition is encountered in
602 the input.  That definition is then used until another definition
603 function for the same name is encountered.  The new definition then
604 replaces the older definition.  A function is defined as follows:
605
606 @example
607 @code{define} @var{name} @code{(} @var{parameters} @code{)} @code{@{} @var{newline}
608     @var{auto_list   statement_list} @code{@}}
609 @end example
610
611 A function call is just an expression of the form
612 "@code{name} @code{(}@var{parameters}@code{)}".
613
614 Parameters are numbers or arrays (an extension).  In the function definition,
615 zero or more parameters are defined by listing their names separated by
616 commas.  Numbers are only call by value parameters.  Arrays are only
617 call by variable.  Arrays are specified in the parameter definition by
618 the notation "@var{name}@code{[ ]}".   In the function call, actual parameters
619 are full expressions for number parameters.  The same notation is used
620 for passing arrays as for defining array parameters.  The named array is
621 passed by variable to the function.  Since function definitions are dynamic,
622 parameter numbers and types are checked when a function is called.  Any
623 mismatch in number or types of parameters will cause a runtime error.
624 A runtime error will also occur for the call to an undefined function.
625
626 The @var{auto_list} is an optional list of variables that are for
627 "local" use.  The syntax of the auto list (if present) is "@code{auto}
628 @var{name}, ... ;".  (The semicolon is optional.)  Each @var{name} is
629 the name of an auto variable.  Arrays may be specified by using the
630 same notation as used in parameters.  These variables have their
631 values pushed onto a stack at the start of the function.  The
632 variables are then initialized to zero and used throughout the
633 execution of the function.  At function exit, these variables are
634 popped so that the original value (at the time of the function call)
635 of these variables are restored.  The parameters are really auto
636 variables that are initialized to a value provided in the function
637 call.  
638 Auto variables are different than traditional local variables
639 because if function A calls function B, B may access function
640 A's auto variables by just using the same name, unless function B has
641 called them auto variables.  Due to the fact that auto variables and
642 parameters are pushed onto a stack, @command{bc} supports recursive functions.
643
644 The function body is a list of @command{bc} statements.  Again, statements
645 are separated by semicolons or newlines.  Return statements cause the
646 termination of a function and the return of a value.  There are two
647 versions of the return statement.  The first form, "@code{return}", returns
648 the value 0 to the calling expression.  The second form, 
649 "@code{return} ( @var{expression} )", computes the value of the expression
650 and returns that value to the calling expression.  There is an implied
651 "@code{return} (0)" at the end of every function.  This allows a function
652 to terminate and return 0 without an explicit @code{return} statement.
653
654 Functions also change the usage of the variable @var{ibase}.  All
655 constants in the function body will be converted using the value of
656 @var{ibase} at the time of the function call.  Changes of @var{ibase}
657 will be ignored during the execution of the function except for the
658 standard function @code{read}, which will always use the current value
659 of @var{ibase} for conversion of numbers.
660
661 As an extension, the format of the definition has been slightly relaxed.
662 The standard requires the opening brace be on the same line as the 
663 @code{define} keyword and all other parts must be on following lines.
664 This version of @command{bc} will allow any number of newlines before and
665 after the opening brace of the function.  For example, the following
666 definitions are legal.
667
668 @example
669    define d (n) @{ return (2*n); @}
670    define d (n)
671        @{ return (2*n); @}
672 @end example
673
674
675 @node Math Library Functions, , Functions, Functions
676 @section Math Library Functions
677
678 If @command{bc} is invoked with the @code{-l} option, a math library is
679 preloaded and the default @var{scale} is set to 20.  The math functions will
680 calculate their results to the scale set at the time of their call.  The
681 math library defines the following functions:
682
683 @table @code
684 @item s (@var{x})
685 The sine of @var{x}, @var{x} is in radians.
686
687 @item c (@var{x})
688 The cosine of @var{x}, @var{x} is in radians.
689
690 @item a (@var{x})
691 The arctangent of @var{x}, arctangent returns radians.
692
693 @item l (@var{x})
694 The natural logarithm of @var{x}.
695
696 @item @var{e} (@var{x})
697 The exponential function of raising @var{e} to the value @var{x}.
698
699 @item @var{j} (@var{n,x})
700 The bessel function of integer order @var{n} of @var{x}.
701 @end table
702
703 @node Examples, Readline and Libedit Options, Functions, Top
704 @chapter Examples
705
706 In /bin/sh,  the following will assign the value of "pi" to the shell
707 variable @var{pi}.
708 @example
709
710 pi=$(echo "scale=10; 4*a(1)" | bc -l)
711
712 @end example
713
714 The following is the definition of the exponential function used in the
715 math library.  This function is written in POSIX @command{bc}.
716
717 @example
718
719 scale = 20
720
721 /* Uses the fact that e^x = (e^(x/2))^2
722    When x is small enough, we use the series:
723      e^x = 1 + x + x^2/2! + x^3/3! + ...
724 */
725
726 define e(x) @{
727   auto  a, d, e, f, i, m, v, z
728
729   /* Check the sign of x. */
730   if (x<0) @{
731     m = 1
732     x = -x
733   @} 
734
735   /* Precondition x. */
736   z = scale;
737   scale = 4 + z + .44*x;
738   while (x > 1) @{
739     f += 1;
740     x /= 2;
741   @}
742
743   /* Initialize the variables. */
744   v = 1+x
745   a = x
746   d = 1
747
748   for (i=2; 1; i++) @{
749     e = (a *= x) / (d *= i)
750     if (e == 0) @{
751       if (f>0) while (f--)  v = v*v;
752       scale = z
753       if (m) return (1/v);
754       return (v/1);
755     @}
756     v += e
757   @}
758 @}
759
760 @end example
761
762 The following is code that uses the extended features of @command{bc} to
763 implement a simple program for calculating checkbook balances.  This
764 program is best kept in a file so that it can be used many times 
765 without having to retype it at every use.
766
767 @example
768
769 scale=2
770 print "\nCheck book program\n!"
771 print "  Remember, deposits are negative transactions.\n"
772 print "  Exit by a 0 transaction.\n\n"
773
774 print "Initial balance? "; bal = read()
775 bal /= 1
776 print "\n"
777 while (1) @{
778   "current balance = "; bal
779   "transaction? "; trans = read()
780   if (trans == 0) break;
781   bal -= trans
782   bal /= 1
783 @}
784 quit
785
786 @end example
787
788
789 The following is the definition of the recursive factorial function.
790
791 @example
792
793 define f (x) @{
794   if (x <= 1) return (1);
795   return (f(x-1) * x);
796 @}
797
798 @end example
799
800 @node Readline and Libedit Options, GNU @command{bc} and Other Implementations, Examples, Top
801 @chapter Readline and Libedit Options
802
803 GNU @command{bc} can be compiled (via a configure option) to use the GNU
804 @command{readline} input editor library or the BSD @command{libedit}
805 library.  This allows the user to do
806 more editing of lines before sending them to @command{bc}.  It also
807 allows for a history of previous lines typed.  When this option is
808 selected, @command{bc} has one more special variable.  This special
809 variable, @var{history} is the number of lines of history retained.  A
810 value of -1 means that an unlimited number of history lines are
811 retained.  This is the default value.  Setting the value of
812 @var{history} to a positive number restricts the number of history lines
813 to the number given.  The value of 0 disables the history feature.  For
814 more information, read the user manuals for the GNU @command{readline},
815 @command{history} and BSD @command{libedit} libraries.  One can not
816 enable both @command{readline} and @command{libedit} at the same time.
817
818 @node GNU @command{bc} and Other Implementations, Limits, Readline and Libedit Options, Top
819 @chapter GNU @command{bc} and Other Implementations
820
821 This version of @command{bc} was implemented from the POSIX P1003.2/D11
822 draft and contains several differences and extensions relative to the
823 draft and traditional implementations.  It is not implemented in the
824 traditional way using @command{dc}.  This version is a single process
825 which parses and runs a byte code translation of the program.  There is
826 an "undocumented" option (-c) that causes the program to output the byte
827 code to the standard output instead of running it.  It was mainly used
828 for debugging the parser and preparing the math library.
829
830 A major source of differences is extensions, where a feature is extended
831 to add more functionality and additions, where new features are added.
832 The following is the list of differences and extensions.
833
834 @table @var
835
836 @item LANG environment
837 This version does not conform to the POSIX standard in the processing
838 of the LANG environment variable and all environment variables starting
839 with LC_.
840
841 @item names
842 Traditional and POSIX @command{bc}
843 have single letter names for functions, variables and arrays.  They have
844 been extended to be multi-character names that start with a letter and
845 may contain letters, numbers and the underscore character.
846
847 @item Strings
848 Strings are not allowed to contain NUL characters.  POSIX says all characters
849 must be included in strings.
850
851 @item last
852 POSIX @command{bc} does not have a \fBlast variable.  Some implementations
853 of @command{bc} use the period (.) in a similar way.  
854
855 @item comparisons
856 POSIX @command{bc} allows comparisons only in the @code{if} statement,
857 the @code{while} statement, and the second expression of the @code{for}
858 statement.  Also, only one relational operation is allowed in each of
859 those statements.
860
861 @item if statement, else clause
862 POSIX @command{bc} does not have an @code{else} clause.
863
864 @item for statement
865 POSIX @command{bc} requires all expressions to be present in the
866 @code{for} statement.
867
868 @item &&, ||, !
869 POSIX @command{bc} does not have the logical operators.
870
871 @item read function
872 POSIX @command{bc} does not have a @code{read} function.
873
874 @item print statement
875 POSIX @command{bc} does not have a @code{print} statement.
876
877 @item continue statement
878 POSIX @command{bc} does not have a continue statement.
879
880 @item array parameters
881 POSIX @command{bc} does not (currently) support array parameters in full.
882 The POSIX grammar allows for arrays in function definitions, but does
883 not provide a method to specify an array as an actual parameter.  (This
884 is most likely an oversight in the grammar.)  Traditional implementations
885 of @command{bc} have only call by value array parameters.
886
887 @item function format
888 POSIX @command{bc} requires the opening brace on the same line as the 
889 @code{define} key word and the @code{auto} statement on the next line.
890
891 @item =+, =-, =*, =/, =%, =^
892 POSIX @command{bc} does not require these "old style" assignment
893 operators to be defined.  This version may allow these "old style"
894 assignments.  Use the @code{limits} statement to see if the installed
895 version supports them.  If it does support the "old style" assignment
896 operators, the statement "a =- 1" will decrement @code{a} by 1 instead
897 of setting @code{a} to the value -1.
898
899 @item spaces in numbers
900 Other implementations of @command{bc} allow spaces in numbers.  For example,
901 "x=1 3" would assign the value 13 to the variable x.  The same statement
902 would cause a syntax error in this version of @command{bc}.
903
904 @item errors and execution
905 This implementation varies from other implementations in terms of what
906 code will be executed when syntax and other errors are found in the
907 program.  If a syntax error is found in a function definition, error
908 recovery tries to find the beginning of a statement and continue to
909 parse the function.  Once a syntax error is found in the function, the
910 function will not be callable and becomes undefined.
911 Syntax errors in the interactive execution code will invalidate the
912 current execution block.  The execution block is terminated by an
913 end of line that appears after a complete sequence of statements.
914 For example, 
915
916 @example
917 a = 1
918 b = 2
919 @end example
920
921 has two execution blocks and
922
923 @example
924 @{ a = 1
925   b = 2 @}
926 @end example
927
928 has one execution block.  Any runtime error will terminate the execution
929 of the current execution block.  A runtime warning will not terminate the
930 current execution block.
931
932 @item Interrupts
933 During an interactive session, the SIGINT signal (usually generated by
934 the control-C character from the terminal) will cause execution of the
935 current execution block to be interrupted.  It will display a "runtime"
936 error indicating which function was interrupted.  After all runtime
937 structures have been cleaned up, a message will be printed to notify the
938 user that @command{bc} is ready for more input.  All previously defined
939 functions remain defined and the value of all non-auto variables are the
940 value at the point of interruption.  All auto variables and function
941 parameters are removed during the clean up process.  During a
942 non-interactive session, the SIGINT signal will terminate the entire run
943 of @command{bc}.
944 @end table
945
946 @node Limits, Environment Variables, GNU @command{bc} and Other Implementations, Top
947 @chapter Limits
948
949 The following are the limits currently in place for this @command{bc}
950 processor.  Some of them may have been changed by an installation.  Use
951 the @code{limits} statement to see the actual values.
952
953 @table @code
954
955 @item BC_BASE_MAX
956 The maximum output base is currently set at 999.  The maximum input base
957 is 16.
958
959 @item BC_DIM_MAX
960 This is currently an arbitrary limit of 65535 as distributed.  Your
961 installation may be different.
962
963 @item BC_SCALE_MAX
964 The number of digits after the decimal point is limited to INT_MAX digits.
965 Also, the number of digits before the decimal point is limited to INT_MAX
966 digits.
967
968 @item BC_STRING_MAX
969 The limit on the number of characters in a string is INT_MAX characters.
970
971 @item exponent
972 The value of the exponent in the raise operation (^) is limited to LONG_MAX.
973
974 @item multiply
975 The multiply routine may yield incorrect results if a number
976 has more than LONG_MAX / 90 total digits.  For 32 bit longs, this number is
977 23,860,929 digits.
978
979 @item variable names
980 The current limit on the number of unique names is 32767 for each of
981 simple variables, arrays and functions.
982 @end table
983
984 @node Environment Variables, , Limits, Top
985 @chapter Environment Variables
986
987 The following environment variables are processed by @command{bc}:
988
989 @table @code
990
991
992 @item POSIXLY_CORRECT
993 This is the same as the -s option (@pxref{Command Line Options}).
994
995 @item BC_ENV_ARGS
996 This is another mechanism to get arguments to @command{bc}.  The format
997 is the same as the command line arguments.  These arguments are
998 processed first, so any files listed in the environent arguments are
999 processed before any command line argument files.  This allows the user
1000 to set up "standard" options and files to be processed at every
1001 invocation of @command{bc}.  The files in the environment variables
1002 would typically contain function definitions for functions the user
1003 wants defined every time @command{bc} is run.
1004
1005 @item BC_LINE_LENGTH
1006 This should be an integer specifing the number of characters in an
1007 output line for numbers. This includes the backslash and newline
1008 characters for long numbers.
1009 @end table
1010
1011 @contents
1012 @bye
1013
1014