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