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