1<!---
2
3SPDX-License-Identifier: BSD-2-Clause
4
5Copyright (c) 2018-2021 Gavin D. Howard and contributors.
6
7Redistribution and use in source and binary forms, with or without
8modification, are permitted provided that the following conditions are met:
9
10* Redistributions of source code must retain the above copyright notice, this
11  list of conditions and the following disclaimer.
12
13* Redistributions in binary form must reproduce the above copyright notice,
14  this list of conditions and the following disclaimer in the documentation
15  and/or other materials provided with the distribution.
16
17THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27POSSIBILITY OF SUCH DAMAGE.
28
29-->
30
31# NAME
32
33bc - arbitrary-precision decimal arithmetic language and calculator
34
35# SYNOPSIS
36
37**bc** [**-ghilPqRsvVw**] [**-\-global-stacks**] [**-\-help**] [**-\-interactive**] [**-\-mathlib**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-quiet**] [**-\-standard**] [**-\-warn**] [**-\-version**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
38
39# DESCRIPTION
40
41bc(1) is an interactive processor for a language first standardized in 1991 by
42POSIX. (The current standard is [here][1].) The language provides unlimited
43precision decimal arithmetic and is somewhat C-like, but there are differences.
44Such differences will be noted in this document.
45
46After parsing and handling options, this bc(1) reads any files given on the
47command line and executes them before reading from **stdin**.
48
49This bc(1) is a drop-in replacement for *any* bc(1), including (and
50especially) the GNU bc(1).
51
52# OPTIONS
53
54The following are the options that bc(1) accepts.
55
56**-g**, **-\-global-stacks**
57
58    Turns the globals **ibase**, **obase**, and **scale** into stacks.
59
60    This has the effect that a copy of the current value of all three are pushed
61    onto a stack for every function call, as well as popped when every function
62    returns. This means that functions can assign to any and all of those
63    globals without worrying that the change will affect other functions.
64    Thus, a hypothetical function named **output(x,b)** that simply printed
65    **x** in base **b** could be written like this:
66
67        define void output(x, b) {
68            obase=b
69            x
70        }
71
72    instead of like this:
73
74        define void output(x, b) {
75            auto c
76            c=obase
77            obase=b
78            x
79            obase=c
80        }
81
82    This makes writing functions much easier.
83
84    However, since using this flag means that functions cannot set **ibase**,
85    **obase**, or **scale** globally, functions that are made to do so cannot
86    work anymore. There are two possible use cases for that, and each has a
87    solution.
88
89    First, if a function is called on startup to turn bc(1) into a number
90    converter, it is possible to replace that capability with various shell
91    aliases. Examples:
92
93        alias d2o="bc -e ibase=A -e obase=8"
94        alias h2b="bc -e ibase=G -e obase=2"
95
96    Second, if the purpose of a function is to set **ibase**, **obase**, or
97    **scale** globally for any other purpose, it could be split into one to
98    three functions (based on how many globals it sets) and each of those
99    functions could return the desired value for a global.
100
101    If the behavior of this option is desired for every run of bc(1), then users
102    could make sure to define **BC_ENV_ARGS** and include this option (see the
103    **ENVIRONMENT VARIABLES** section for more details).
104
105    If **-s**, **-w**, or any equivalents are used, this option is ignored.
106
107    This is a **non-portable extension**.
108
109**-h**, **-\-help**
110
111:   Prints a usage message and quits.
112
113**-i**, **-\-interactive**
114
115:   Forces interactive mode. (See the **INTERACTIVE MODE** section.)
116
117    This is a **non-portable extension**.
118
119**-l**, **-\-mathlib**
120
121:   Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
122    math library before running any code, including any expressions or files
123    specified on the command line.
124
125    To learn what is in the library, see the **LIBRARY** section.
126
127**-P**, **-\-no-prompt**
128
129:   Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
130    See the **TTY MODE** section.) This is mostly for those users that do not
131    want a prompt or are not used to having them in bc(1). Most of those users
132    would want to put this option in **BC_ENV_ARGS** (see the
133    **ENVIRONMENT VARIABLES** section).
134
135    This is a **non-portable extension**.
136
137**-R**, **-\-no-read-prompt**
138
139:   Disables the read prompt in TTY mode. (The read prompt is only enabled in
140    TTY mode. See the **TTY MODE** section.) This is mostly for those users that
141    do not want a read prompt or are not used to having them in bc(1). Most of
142    those users would want to put this option in **BC_ENV_ARGS** (see the
143    **ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
144    lines of bc(1) scripts that prompt for user input.
145
146    This option does not disable the regular prompt because the read prompt is
147    only used when the **read()** built-in function is called.
148
149    This is a **non-portable extension**.
150
151**-q**, **-\-quiet**
152
153:   This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
154    Without this option, GNU bc(1) prints a copyright header. This bc(1) only
155    prints the copyright header if one or more of the **-v**, **-V**, or
156    **-\-version** options are given.
157
158    This is a **non-portable extension**.
159
160**-s**, **-\-standard**
161
162:   Process exactly the language defined by the [standard][1] and error if any
163    extensions are used.
164
165    This is a **non-portable extension**.
166
167**-v**, **-V**, **-\-version**
168
169:   Print the version information (copyright header) and exit.
170
171    This is a **non-portable extension**.
172
173**-w**, **-\-warn**
174
175:   Like **-s** and **-\-standard**, except that warnings (and not errors) are
176    printed for non-standard extensions and execution continues normally.
177
178    This is a **non-portable extension**.
179
180**-e** *expr*, **-\-expression**=*expr*
181
182:   Evaluates *expr*. If multiple expressions are given, they are evaluated in
183    order. If files are given as well (see below), the expressions and files are
184    evaluated in the order given. This means that if a file is given before an
185    expression, the file is read in and evaluated first.
186
187    If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
188    see the **ENVIRONMENT VARIABLES** section), then after processing all
189    expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
190    as an argument at least once to **-f** or **-\-file**, whether on the
191    command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
192    **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
193    or equivalent is given, bc(1) will give a fatal error and exit.
194
195    This is a **non-portable extension**.
196
197**-f** *file*, **-\-file**=*file*
198
199:   Reads in *file* and evaluates it, line by line, as though it were read
200    through **stdin**. If expressions are also given (see above), the
201    expressions are evaluated in the order given.
202
203    If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
204    see the **ENVIRONMENT VARIABLES** section), then after processing all
205    expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
206    as an argument at least once to **-f** or **-\-file**. However, if any other
207    **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
208    **-f-** or equivalent is given, bc(1) will give a fatal error and exit.
209
210    This is a **non-portable extension**.
211
212All long options are **non-portable extensions**.
213
214# STDOUT
215
216Any non-error output is written to **stdout**. In addition, if history (see the
217**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
218both are output to **stdout**.
219
220**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
221error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
222**stdout** is closed, as in **bc <file> >&-**, it will quit with an error. This
223is done so that bc(1) can report problems when **stdout** is redirected to a
224file.
225
226If there are scripts that depend on the behavior of other bc(1) implementations,
227it is recommended that those scripts be changed to redirect **stdout** to
228**/dev/null**.
229
230# STDERR
231
232Any error output is written to **stderr**.
233
234**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
235error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
236**stderr** is closed, as in **bc <file> 2>&-**, it will quit with an error. This
237is done so that bc(1) can exit with an error code when **stderr** is redirected
238to a file.
239
240If there are scripts that depend on the behavior of other bc(1) implementations,
241it is recommended that those scripts be changed to redirect **stderr** to
242**/dev/null**.
243
244# SYNTAX
245
246The syntax for bc(1) programs is mostly C-like, with some differences. This
247bc(1) follows the [POSIX standard][1], which is a much more thorough resource
248for the language this bc(1) accepts. This section is meant to be a summary and a
249listing of all the extensions to the standard.
250
251In the sections below, **E** means expression, **S** means statement, and **I**
252means identifier.
253
254Identifiers (**I**) start with a lowercase letter and can be followed by any
255number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
256(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
257Identifiers with more than one character (letter) are a
258**non-portable extension**.
259
260**ibase** is a global variable determining how to interpret constant numbers. It
261is the "input" base, or the number base used for interpreting input numbers.
262**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
263(**-\-warn**) flags were not given on the command line, the max allowable value
264for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
265**ibase** is **2**. The max allowable value for **ibase** can be queried in
266bc(1) programs with the **maxibase()** built-in function.
267
268**obase** is a global variable determining how to output results. It is the
269"output" base, or the number base used for outputting numbers. **obase** is
270initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
271can be queried in bc(1) programs with the **maxobase()** built-in function. The
272min allowable value for **obase** is **2**. Values are output in the specified
273base.
274
275The *scale* of an expression is the number of digits in the result of the
276expression right of the decimal point, and **scale** is a global variable that
277sets the precision of any operations, with exceptions. **scale** is initially
278**0**. **scale** cannot be negative. The max allowable value for **scale** is
279**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
280built-in function.
281
282bc(1) has both *global* variables and *local* variables. All *local*
283variables are local to the function; they are parameters or are introduced in
284the **auto** list of a function (see the **FUNCTIONS** section). If a variable
285is accessed which is not a parameter or in the **auto** list, it is assumed to
286be *global*. If a parent function has a *local* variable version of a variable
287that a child function considers *global*, the value of that *global* variable in
288the child function is the value of the variable in the parent function, not the
289value of the actual *global* variable.
290
291All of the above applies to arrays as well.
292
293The value of a statement that is an expression (i.e., any of the named
294expressions or operands) is printed unless the lowest precedence operator is an
295assignment operator *and* the expression is notsurrounded by parentheses.
296
297The value that is printed is also assigned to the special variable **last**. A
298single dot (**.**) may also be used as a synonym for **last**. These are
299**non-portable extensions**.
300
301Either semicolons or newlines may separate statements.
302
303## Comments
304
305There are two kinds of comments:
306
3071.	Block comments are enclosed in **/\*** and **\*/**.
3082.	Line comments go from **#** until, and not including, the next newline. This
309	is a **non-portable extension**.
310
311## Named Expressions
312
313The following are named expressions in bc(1):
314
3151.	Variables: **I**
3162.	Array Elements: **I[E]**
3173.	**ibase**
3184.	**obase**
3195.	**scale**
3206.	**last** or a single dot (**.**)
321
322Number 6 is a **non-portable extension**.
323
324Variables and arrays do not interfere; users can have arrays named the same as
325variables. This also applies to functions (see the **FUNCTIONS** section), so a
326user can have a variable, array, and function that all have the same name, and
327they will not shadow each other, whether inside of functions or not.
328
329Named expressions are required as the operand of **increment**/**decrement**
330operators  and as the left side of **assignment** operators (see the *Operators*
331subsection).
332
333## Operands
334
335The following are valid operands in bc(1):
336
3371.	Numbers (see the *Numbers* subsection below).
3382.	Array indices (**I[E]**).
3393.	**(E)**: The value of **E** (used to change precedence).
3404.	**sqrt(E)**: The square root of **E**. **E** must be non-negative.
3415.	**length(E)**: The number of significant decimal digits in **E**.
3426.	**length(I[])**: The number of elements in the array **I**. This is a
343	**non-portable extension**.
3447.	**scale(E)**: The *scale* of **E**.
3458.	**abs(E)**: The absolute value of **E**. This is a **non-portable
346	extension**.
3479.	**I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
348	a non-**void** function (see the *Void Functions* subsection of the
349	**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
350	**I[]**, which will automatically be turned into array references (see the
351	*Array References* subsection of the **FUNCTIONS** section) if the
352	corresponding parameter in the function definition is an array reference.
35310.	**read()**: Reads a line from **stdin** and uses that as an expression. The
354	result of that expression is the result of the **read()** operand. This is a
355	**non-portable extension**.
35611.	**maxibase()**: The max allowable **ibase**. This is a **non-portable
357	extension**.
35812.	**maxobase()**: The max allowable **obase**. This is a **non-portable
359	extension**.
36013.	**maxscale()**: The max allowable **scale**. This is a **non-portable
361	extension**.
362
363## Numbers
364
365Numbers are strings made up of digits, uppercase letters, and at most **1**
366period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
367letters are equal to **9** + their position in the alphabet (i.e., **A** equals
368**10**, or **9+1**). If a digit or letter makes no sense with the current value
369of **ibase**, they are set to the value of the highest valid digit in **ibase**.
370
371Single-character numbers (i.e., **A** alone) take the value that they would have
372if they were valid digits, regardless of the value of **ibase**. This means that
373**A** alone always equals decimal **10** and **Z** alone always equals decimal
374**35**.
375
376## Operators
377
378The following arithmetic and logical operators can be used. They are listed in
379order of decreasing precedence. Operators in the same group have the same
380precedence.
381
382**++** **-\-**
383
384:   Type: Prefix and Postfix
385
386    Associativity: None
387
388    Description: **increment**, **decrement**
389
390**-** **!**
391
392:   Type: Prefix
393
394    Associativity: None
395
396    Description: **negation**, **boolean not**
397
398**\^**
399
400:   Type: Binary
401
402    Associativity: Right
403
404    Description: **power**
405
406**\*** **/** **%**
407
408:   Type: Binary
409
410    Associativity: Left
411
412    Description: **multiply**, **divide**, **modulus**
413
414**+** **-**
415
416:   Type: Binary
417
418    Associativity: Left
419
420    Description: **add**, **subtract**
421
422**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
423
424:   Type: Binary
425
426    Associativity: Right
427
428    Description: **assignment**
429
430**==** **\<=** **\>=** **!=** **\<** **\>**
431
432:   Type: Binary
433
434    Associativity: Left
435
436    Description: **relational**
437
438**&&**
439
440:   Type: Binary
441
442    Associativity: Left
443
444    Description: **boolean and**
445
446**||**
447
448:   Type: Binary
449
450    Associativity: Left
451
452    Description: **boolean or**
453
454The operators will be described in more detail below.
455
456**++** **-\-**
457
458:   The prefix and postfix **increment** and **decrement** operators behave
459    exactly like they would in C. They require a named expression (see the
460    *Named Expressions* subsection) as an operand.
461
462    The prefix versions of these operators are more efficient; use them where
463    possible.
464
465**-**
466
467:   The **negation** operator returns **0** if a user attempts to negate any
468    expression with the value **0**. Otherwise, a copy of the expression with
469    its sign flipped is returned.
470
471**!**
472
473:   The **boolean not** operator returns **1** if the expression is **0**, or
474    **0** otherwise.
475
476    This is a **non-portable extension**.
477
478**\^**
479
480:   The **power** operator (not the **exclusive or** operator, as it would be in
481    C) takes two expressions and raises the first to the power of the value of
482    the second. The *scale* of the result is equal to **scale**.
483
484    The second expression must be an integer (no *scale*), and if it is
485    negative, the first value must be non-zero.
486
487**\***
488
489:   The **multiply** operator takes two expressions, multiplies them, and
490    returns the product. If **a** is the *scale* of the first expression and
491    **b** is the *scale* of the second expression, the *scale* of the result is
492    equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
493    the obvious values.
494
495**/**
496
497:   The **divide** operator takes two expressions, divides them, and returns the
498    quotient. The *scale* of the result shall be the value of **scale**.
499
500    The second expression must be non-zero.
501
502**%**
503
504:   The **modulus** operator takes two expressions, **a** and **b**, and
505    evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
506    result of step 1 to calculate **a-(a/b)\*b** to *scale*
507    **max(scale+scale(b),scale(a))**.
508
509    The second expression must be non-zero.
510
511**+**
512
513:   The **add** operator takes two expressions, **a** and **b**, and returns the
514    sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
515
516**-**
517
518:   The **subtract** operator takes two expressions, **a** and **b**, and
519    returns the difference, with a *scale* equal to the max of the *scale*s of
520    **a** and **b**.
521
522**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
523
524:   The **assignment** operators take two expressions, **a** and **b** where
525    **a** is a named expression (see the *Named Expressions* subsection).
526
527    For **=**, **b** is copied and the result is assigned to **a**. For all
528    others, **a** and **b** are applied as operands to the corresponding
529    arithmetic operator and the result is assigned to **a**.
530
531**==** **\<=** **\>=** **!=** **\<** **\>**
532
533:   The **relational** operators compare two expressions, **a** and **b**, and
534    if the relation holds, according to C language semantics, the result is
535    **1**. Otherwise, it is **0**.
536
537    Note that unlike in C, these operators have a lower precedence than the
538    **assignment** operators, which means that **a=b\>c** is interpreted as
539    **(a=b)\>c**.
540
541    Also, unlike the [standard][1] requires, these operators can appear anywhere
542    any other expressions can be used. This allowance is a
543    **non-portable extension**.
544
545**&&**
546
547:   The **boolean and** operator takes two expressions and returns **1** if both
548    expressions are non-zero, **0** otherwise.
549
550    This is *not* a short-circuit operator.
551
552    This is a **non-portable extension**.
553
554**||**
555
556:   The **boolean or** operator takes two expressions and returns **1** if one
557    of the expressions is non-zero, **0** otherwise.
558
559    This is *not* a short-circuit operator.
560
561    This is a **non-portable extension**.
562
563## Statements
564
565The following items are statements:
566
5671.	**E**
5682.	**{** **S** **;** ... **;** **S** **}**
5693.	**if** **(** **E** **)** **S**
5704.	**if** **(** **E** **)** **S** **else** **S**
5715.	**while** **(** **E** **)** **S**
5726.	**for** **(** **E** **;** **E** **;** **E** **)** **S**
5737.	An empty statement
5748.	**break**
5759.	**continue**
57610.	**quit**
57711.	**halt**
57812.	**limits**
57913.	A string of characters, enclosed in double quotes
58014.	**print** **E** **,** ... **,** **E**
58115.	**I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
582	a **void** function (see the *Void Functions* subsection of the
583	**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
584	**I[]**, which will automatically be turned into array references (see the
585	*Array References* subsection of the **FUNCTIONS** section) if the
586	corresponding parameter in the function definition is an array reference.
587
588Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**.
589
590Also, as a **non-portable extension**, any or all of the expressions in the
591header of a for loop may be omitted. If the condition (second expression) is
592omitted, it is assumed to be a constant **1**.
593
594The **break** statement causes a loop to stop iterating and resume execution
595immediately following a loop. This is only allowed in loops.
596
597The **continue** statement causes a loop iteration to stop early and returns to
598the start of the loop, including testing the loop condition. This is only
599allowed in loops.
600
601The **if** **else** statement does the same thing as in C.
602
603The **quit** statement causes bc(1) to quit, even if it is on a branch that will
604not be executed (it is a compile-time command).
605
606The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
607if it is on a branch of an **if** statement that is not executed, bc(1) does not
608quit.)
609
610The **limits** statement prints the limits that this bc(1) is subject to. This
611is like the **quit** statement in that it is a compile-time command.
612
613An expression by itself is evaluated and printed, followed by a newline.
614
615## Print Statement
616
617The "expressions" in a **print** statement may also be strings. If they are, there
618are backslash escape sequences that are interpreted specially. What those
619sequences are, and what they cause to be printed, are shown below:
620
621-------- -------
622**\\a**  **\\a**
623**\\b**  **\\b**
624**\\\\** **\\**
625**\\e**  **\\**
626**\\f**  **\\f**
627**\\n**  **\\n**
628**\\q**  **"**
629**\\r**  **\\r**
630**\\t**  **\\t**
631-------- -------
632
633Any other character following a backslash causes the backslash and character to
634be printed as-is.
635
636Any non-string expression in a print statement shall be assigned to **last**,
637like any other expression that is printed.
638
639## Order of Evaluation
640
641All expressions in a statment are evaluated left to right, except as necessary
642to maintain order of operations. This means, for example, assuming that **i** is
643equal to **0**, in the expression
644
645    a[i++] = i++
646
647the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
648at the end of the expression.
649
650This includes function arguments. Thus, assuming **i** is equal to **0**, this
651means that in the expression
652
653    x(i++, i++)
654
655the first argument passed to **x()** is **0**, and the second argument is **1**,
656while **i** is equal to **2** before the function starts executing.
657
658# FUNCTIONS
659
660Function definitions are as follows:
661
662```
663define I(I,...,I){
664	auto I,...,I
665	S;...;S
666	return(E)
667}
668```
669
670Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
671make a parameter or **auto** var an array, and any **I** in the parameter list
672may be replaced with **\*I[]** to make a parameter an array reference. Callers
673of functions that take array references should not put an asterisk in the call;
674they must be called with just **I[]** like normal array parameters and will be
675automatically converted into references.
676
677As a **non-portable extension**, the opening brace of a **define** statement may
678appear on the next line.
679
680As a **non-portable extension**, the return statement may also be in one of the
681following forms:
682
6831.	**return**
6842.	**return** **(** **)**
6853.	**return** **E**
686
687The first two, or not specifying a **return** statement, is equivalent to
688**return (0)**, unless the function is a **void** function (see the *Void
689Functions* subsection below).
690
691## Void Functions
692
693Functions can also be **void** functions, defined as follows:
694
695```
696define void I(I,...,I){
697	auto I,...,I
698	S;...;S
699	return
700}
701```
702
703They can only be used as standalone expressions, where such an expression would
704be printed alone, except in a print statement.
705
706Void functions can only use the first two **return** statements listed above.
707They can also omit the return statement entirely.
708
709The word "void" is not treated as a keyword; it is still possible to have
710variables, arrays, and functions named **void**. The word "void" is only
711treated specially right after the **define** keyword.
712
713This is a **non-portable extension**.
714
715## Array References
716
717For any array in the parameter list, if the array is declared in the form
718
719```
720*I[]
721```
722
723it is a **reference**. Any changes to the array in the function are reflected,
724when the function returns, to the array that was passed in.
725
726Other than this, all function arguments are passed by value.
727
728This is a **non-portable extension**.
729
730# LIBRARY
731
732All of the functions below  are available when the **-l** or **-\-mathlib**
733command-line flags are given.
734
735## Standard Library
736
737The [standard][1] defines the following functions for the math library:
738
739**s(x)**
740
741:   Returns the sine of **x**, which is assumed to be in radians.
742
743    This is a transcendental function (see the *Transcendental Functions*
744    subsection below).
745
746**c(x)**
747
748:   Returns the cosine of **x**, which is assumed to be in radians.
749
750    This is a transcendental function (see the *Transcendental Functions*
751    subsection below).
752
753**a(x)**
754
755:   Returns the arctangent of **x**, in radians.
756
757    This is a transcendental function (see the *Transcendental Functions*
758    subsection below).
759
760**l(x)**
761
762:   Returns the natural logarithm of **x**.
763
764    This is a transcendental function (see the *Transcendental Functions*
765    subsection below).
766
767**e(x)**
768
769:   Returns the mathematical constant **e** raised to the power of **x**.
770
771    This is a transcendental function (see the *Transcendental Functions*
772    subsection below).
773
774**j(x, n)**
775
776:   Returns the bessel integer order **n** (truncated) of **x**.
777
778    This is a transcendental function (see the *Transcendental Functions*
779    subsection below).
780
781## Transcendental Functions
782
783All transcendental functions can return slightly inaccurate results (up to 1
784[ULP][4]). This is unavoidable, and [this article][5] explains why it is
785impossible and unnecessary to calculate exact results for the transcendental
786functions.
787
788Because of the possible inaccuracy, I recommend that users call those functions
789with the precision (**scale**) set to at least 1 higher than is necessary. If
790exact results are *absolutely* required, users can double the precision
791(**scale**) and then truncate.
792
793The transcendental functions in the standard math library are:
794
795* **s(x)**
796* **c(x)**
797* **a(x)**
798* **l(x)**
799* **e(x)**
800* **j(x, n)**
801
802# RESET
803
804When bc(1) encounters an error or a signal that it has a non-default handler
805for, it resets. This means that several things happen.
806
807First, any functions that are executing are stopped and popped off the stack.
808The behavior is not unlike that of exceptions in programming languages. Then
809the execution point is set so that any code waiting to execute (after all
810functions returned) is skipped.
811
812Thus, when bc(1) resets, it skips any remaining code waiting to be executed.
813Then, if it is interactive mode, and the error was not a fatal error (see the
814**EXIT STATUS** section), it asks for more input; otherwise, it exits with the
815appropriate return code.
816
817Note that this reset behavior is different from the GNU bc(1), which attempts to
818start executing the statement right after the one that caused an error.
819
820# PERFORMANCE
821
822Most bc(1) implementations use **char** types to calculate the value of **1**
823decimal digit at a time, but that can be slow. This bc(1) does something
824different.
825
826It uses large integers to calculate more than **1** decimal digit at a time. If
827built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
828**64**, then each integer has **9** decimal digits. If built in an environment
829where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
830value (the number of decimal digits per large integer) is called
831**BC_BASE_DIGS**.
832
833The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
834the **limits** statement.
835
836In addition, this bc(1) uses an even larger integer for overflow checking. This
837integer type depends on the value of **BC_LONG_BIT**, but is always at least
838twice as large as the integer type used to store digits.
839
840# LIMITS
841
842The following are the limits on bc(1):
843
844**BC_LONG_BIT**
845
846:   The number of bits in the **long** type in the environment where bc(1) was
847    built. This determines how many decimal digits can be stored in a single
848    large integer (see the **PERFORMANCE** section).
849
850**BC_BASE_DIGS**
851
852:   The number of decimal digits per large integer (see the **PERFORMANCE**
853    section). Depends on **BC_LONG_BIT**.
854
855**BC_BASE_POW**
856
857:   The max decimal number that each large integer can store (see
858    **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
859
860**BC_OVERFLOW_MAX**
861
862:   The max number that the overflow type (see the **PERFORMANCE** section) can
863    hold. Depends on **BC_LONG_BIT**.
864
865**BC_BASE_MAX**
866
867:   The maximum output base. Set at **BC_BASE_POW**.
868
869**BC_DIM_MAX**
870
871:   The maximum size of arrays. Set at **SIZE_MAX-1**.
872
873**BC_SCALE_MAX**
874
875:   The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
876
877**BC_STRING_MAX**
878
879:   The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
880
881**BC_NAME_MAX**
882
883:   The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
884
885**BC_NUM_MAX**
886
887:   The maximum length of a number (in decimal digits), which includes digits
888    after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
889
890Exponent
891
892:   The maximum allowable exponent (positive or negative). Set at
893    **BC_OVERFLOW_MAX**.
894
895Number of vars
896
897:   The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
898
899The actual values can be queried with the **limits** statement.
900
901These limits are meant to be effectively non-existent; the limits are so large
902(at least on 64-bit machines) that there should not be any point at which they
903become a problem. In fact, memory should be exhausted before these limits should
904be hit.
905
906# ENVIRONMENT VARIABLES
907
908bc(1) recognizes the following environment variables:
909
910**POSIXLY_CORRECT**
911
912:   If this variable exists (no matter the contents), bc(1) behaves as if
913    the **-s** option was given.
914
915**BC_ENV_ARGS**
916
917:   This is another way to give command-line arguments to bc(1). They should be
918    in the same format as all other command-line arguments. These are always
919    processed first, so any files given in **BC_ENV_ARGS** will be processed
920    before arguments and files given on the command-line. This gives the user
921    the ability to set up "standard" options and files to be used at every
922    invocation. The most useful thing for such files to contain would be useful
923    functions that the user might want every time bc(1) runs.
924
925    The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
926    but it does not understand escape sequences. For example, the string
927    **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
928    **"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
929
930    The quote parsing will handle either kind of quotes, **'** or **"**. Thus,
931    if you have a file with any number of single quotes in the name, you can use
932    double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice
933    versa if you have a file with double quotes. However, handling a file with
934    both kinds of quotes in **BC_ENV_ARGS** is not supported due to the
935    complexity of the parsing, though such files are still supported on the
936    command-line where the parsing is done by the shell.
937
938**BC_LINE_LENGTH**
939
940:   If this environment variable exists and contains an integer that is greater
941    than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
942    lines to that length, including the backslash (**\\**). The default line
943    length is **70**.
944
945# EXIT STATUS
946
947bc(1) returns the following exit statuses:
948
949**0**
950
951:   No error.
952
953**1**
954
955:   A math error occurred. This follows standard practice of using **1** for
956    expected errors, since math errors will happen in the process of normal
957    execution.
958
959    Math errors include divide by **0**, taking the square root of a negative
960    number, attempting to convert a negative number to a hardware integer,
961    overflow when converting a number to a hardware integer, and attempting to
962    use a non-integer where an integer is required.
963
964    Converting to a hardware integer happens for the second operand of the power
965    (**\^**) operator and the corresponding assignment operator.
966
967**2**
968
969:   A parse error occurred.
970
971    Parse errors include unexpected **EOF**, using an invalid character, failing
972    to find the end of a string or comment, using a token where it is invalid,
973    giving an invalid expression, giving an invalid print statement, giving an
974    invalid function definition, attempting to assign to an expression that is
975    not a named expression (see the *Named Expressions* subsection of the
976    **SYNTAX** section), giving an invalid **auto** list, having a duplicate
977    **auto**/function parameter, failing to find the end of a code block,
978    attempting to return a value from a **void** function, attempting to use a
979    variable as a reference, and using any extensions when the option **-s** or
980    any equivalents were given.
981
982**3**
983
984:   A runtime error occurred.
985
986    Runtime errors include assigning an invalid number to **ibase**, **obase**,
987    or **scale**; give a bad expression to a **read()** call, calling **read()**
988    inside of a **read()** call, type errors, passing the wrong number of
989    arguments to functions, attempting to call an undefined function, and
990    attempting to use a **void** function call as a value in an expression.
991
992**4**
993
994:   A fatal error occurred.
995
996    Fatal errors include memory allocation errors, I/O errors, failing to open
997    files, attempting to use files that do not have only ASCII characters (bc(1)
998    only accepts ASCII characters), attempting to open a directory as a file,
999    and giving invalid command-line options.
1000
1001The exit status **4** is special; when a fatal error occurs, bc(1) always exits
1002and returns **4**, no matter what mode bc(1) is in.
1003
1004The other statuses will only be returned when bc(1) is not in interactive mode
1005(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the
1006**RESET** section) and accepts more input when one of those errors occurs in
1007interactive mode. This is also the case when interactive mode is forced by the
1008**-i** flag or **-\-interactive** option.
1009
1010These exit statuses allow bc(1) to be used in shell scripting with error
1011checking, and its normal behavior can be forced by using the **-i** flag or
1012**-\-interactive** option.
1013
1014# INTERACTIVE MODE
1015
1016Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
1017Interactive mode is turned on automatically when both **stdin** and **stdout**
1018are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
1019turn it on in other cases.
1020
1021In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
1022section), and in normal execution, flushes **stdout** as soon as execution is
1023done for the current input.
1024
1025# TTY MODE
1026
1027If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns
1028on "TTY mode."
1029
1030TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY**
1031section). It is also required to enable special handling for **SIGINT** signals.
1032
1033The prompt is enabled in TTY mode.
1034
1035TTY mode is different from interactive mode because interactive mode is required
1036in the [bc(1) specification][1], and interactive mode requires only **stdin**
1037and **stdout** to be connected to a terminal.
1038
1039# SIGNAL HANDLING
1040
1041Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If
1042bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the
1043**RESET** section). Otherwise, it will clean up and exit.
1044
1045Note that "current input" can mean one of two things. If bc(1) is processing
1046input from **stdin** in TTY mode, it will ask for more input. If bc(1) is
1047processing input from a file in TTY mode, it will stop processing the file and
1048start processing the next file, if one exists, or ask for input from **stdin**
1049if no other file exists.
1050
1051This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
1052can seem as though bc(1) did not respond to the signal since it will immediately
1053start executing the next file. This is by design; most files that users execute
1054when interacting with bc(1) have function definitions, which are quick to parse.
1055If a file takes a long time to execute, there may be a bug in that file. The
1056rest of the files could still be executed without problem, allowing the user to
1057continue.
1058
1059**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
1060default handler for all other signals. The one exception is **SIGHUP**; in that
1061case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and
1062exit.
1063
1064# COMMAND LINE HISTORY
1065
1066bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see
1067the **TTY MODE** section), history is enabled. Previous lines can be recalled
1068and edited with the arrow keys.
1069
1070**Note**: tabs are converted to 8 spaces.
1071
1072# LOCALES
1073
1074This bc(1) ships with support for adding error messages for different locales
1075and thus, supports **LC_MESSAGES**.
1076
1077# SEE ALSO
1078
1079dc(1)
1080
1081# STANDARDS
1082
1083bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
1084specification. The flags **-efghiqsvVw**, all long options, and the extensions
1085noted above are extensions to that specification.
1086
1087Note that the specification explicitly says that bc(1) only accepts numbers that
1088use a period (**.**) as a radix point, regardless of the value of
1089**LC_NUMERIC**.
1090
1091This bc(1) supports error messages for different locales, and thus, it supports
1092**LC_MESSAGES**.
1093
1094# BUGS
1095
1096None are known. Report bugs at https://git.yzena.com/gavin/bc.
1097
1098# AUTHORS
1099
1100Gavin D. Howard <gavin@yzena.com> and contributors.
1101
1102[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
1103[2]: https://www.gnu.org/software/bc/
1104[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
1105[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
1106[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
1107[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
1108