xref: /freebsd/contrib/bc/manuals/bc/E.1.md (revision c1d255d3)
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 especially)
50the GNU bc(1).
51
52**Note**: If running this bc(1) on *any* script meant for another bc(1) gives a
53parse error, it is probably because a word this bc(1) reserves as a keyword is
54used as the name of a function, variable, or array. To fix that, use the
55command-line option **-r** *keyword*, where *keyword* is the keyword that is
56used as a name in the script. For more information, see the **OPTIONS** section.
57
58If parsing scripts meant for other bc(1) implementations still does not work,
59that is a bug and should be reported. See the **BUGS** section.
60
61# OPTIONS
62
63The following are the options that bc(1) accepts.
64
65**-g**, **-\-global-stacks**
66
67:   Turns the globals **ibase**, **obase**, and **scale** into stacks.
68
69    This has the effect that a copy of the current value of all three are pushed
70    onto a stack for every function call, as well as popped when every function
71    returns. This means that functions can assign to any and all of those
72    globals without worrying that the change will affect other functions.
73    Thus, a hypothetical function named **output(x,b)** that simply printed
74    **x** in base **b** could be written like this:
75
76        define void output(x, b) {
77            obase=b
78            x
79        }
80
81    instead of like this:
82
83        define void output(x, b) {
84            auto c
85            c=obase
86            obase=b
87            x
88            obase=c
89        }
90
91    This makes writing functions much easier.
92
93    However, since using this flag means that functions cannot set **ibase**,
94    **obase**, or **scale** globally, functions that are made to do so cannot
95    work anymore. There are two possible use cases for that, and each has a
96    solution.
97
98    First, if a function is called on startup to turn bc(1) into a number
99    converter, it is possible to replace that capability with various shell
100    aliases. Examples:
101
102        alias d2o="bc -e ibase=A -e obase=8"
103        alias h2b="bc -e ibase=G -e obase=2"
104
105    Second, if the purpose of a function is to set **ibase**, **obase**, or
106    **scale** globally for any other purpose, it could be split into one to
107    three functions (based on how many globals it sets) and each of those
108    functions could return the desired value for a global.
109
110    If the behavior of this option is desired for every run of bc(1), then users
111    could make sure to define **BC_ENV_ARGS** and include this option (see the
112    **ENVIRONMENT VARIABLES** section for more details).
113
114    If **-s**, **-w**, or any equivalents are used, this option is ignored.
115
116    This is a **non-portable extension**.
117
118**-h**, **-\-help**
119
120:   Prints a usage message and quits.
121
122**-i**, **-\-interactive**
123
124:   Forces interactive mode. (See the **INTERACTIVE MODE** section.)
125
126    This is a **non-portable extension**.
127
128**-l**, **-\-mathlib**
129
130:   Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
131    math library before running any code, including any expressions or files
132    specified on the command line.
133
134    To learn what is in the library, see the **LIBRARY** section.
135
136**-P**, **-\-no-prompt**
137
138:   Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
139    See the **TTY MODE** section.) This is mostly for those users that do not
140    want a prompt or are not used to having them in bc(1). Most of those users
141    would want to put this option in **BC_ENV_ARGS** (see the
142    **ENVIRONMENT VARIABLES** section).
143
144    These options override the **BC_PROMPT** and **BC_TTY_MODE** environment
145    variables (see the **ENVIRONMENT VARIABLES** section).
146
147    This is a **non-portable extension**.
148
149**-R**, **-\-no-read-prompt**
150
151:   Disables the read prompt in TTY mode. (The read prompt is only enabled in
152    TTY mode. See the **TTY MODE** section.) This is mostly for those users that
153    do not want a read prompt or are not used to having them in bc(1). Most of
154    those users would want to put this option in **BC_ENV_ARGS** (see the
155    **ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
156    lines of bc(1) scripts that prompt for user input.
157
158    This option does not disable the regular prompt because the read prompt is
159    only used when the **read()** built-in function is called.
160
161    These options *do* override the **BC_PROMPT** and **BC_TTY_MODE**
162    environment variables (see the **ENVIRONMENT VARIABLES** section), but only
163    for the read prompt.
164
165    This is a **non-portable extension**.
166
167**-r** *keyword*, **-\-redefine**=*keyword*
168
169:   Redefines *keyword* in order to allow it to be used as a function, variable,
170    or array name. This is useful when this bc(1) gives parse errors when
171    parsing scripts meant for other bc(1) implementations.
172
173    The keywords this bc(1) allows to be redefined are:
174
175    * **abs**
176    * **asciify**
177    * **continue**
178    * **divmod**
179    * **else**
180    * **halt**
181    * **last**
182    * **limits**
183    * **maxibase**
184    * **maxobase**
185    * **maxscale**
186    * **modexp**
187    * **print**
188    * **read**
189	* **stream**
190
191    If any of those keywords are used as a function, variable, or array name in
192    a script, use this option with the keyword as the argument. If multiple are
193    used, use this option for all of them; it can be used multiple times.
194
195    Keywords are *not* redefined when parsing the builtin math library (see the
196    **LIBRARY** section).
197
198    It is a fatal error to redefine keywords mandated by the POSIX standard. It
199    is a fatal error to attempt to redefine words that this bc(1) does not
200    reserve as keywords.
201
202**-q**, **-\-quiet**
203
204:   This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
205    Without this option, GNU bc(1) prints a copyright header. This bc(1) only
206    prints the copyright header if one or more of the **-v**, **-V**, or
207    **-\-version** options are given.
208
209    This is a **non-portable extension**.
210
211**-s**, **-\-standard**
212
213:   Process exactly the language defined by the [standard][1] and error if any
214    extensions are used.
215
216    This is a **non-portable extension**.
217
218**-v**, **-V**, **-\-version**
219
220:   Print the version information (copyright header) and exit.
221
222    This is a **non-portable extension**.
223
224**-w**, **-\-warn**
225
226:   Like **-s** and **-\-standard**, except that warnings (and not errors) are
227    printed for non-standard extensions and execution continues normally.
228
229    This is a **non-portable extension**.
230
231**-e** *expr*, **-\-expression**=*expr*
232
233:   Evaluates *expr*. If multiple expressions are given, they are evaluated in
234    order. If files are given as well (see below), the expressions and files are
235    evaluated in the order given. This means that if a file is given before an
236    expression, the file is read in and evaluated first.
237
238    If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
239    see the **ENVIRONMENT VARIABLES** section), then after processing all
240    expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
241    as an argument at least once to **-f** or **-\-file**, whether on the
242    command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
243    **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
244    or equivalent is given, bc(1) will give a fatal error and exit.
245
246    This is a **non-portable extension**.
247
248**-f** *file*, **-\-file**=*file*
249
250:   Reads in *file* and evaluates it, line by line, as though it were read
251    through **stdin**. If expressions are also given (see above), the
252    expressions are evaluated in the order given.
253
254    If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
255    see the **ENVIRONMENT VARIABLES** section), then after processing all
256    expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
257    as an argument at least once to **-f** or **-\-file**. However, if any other
258    **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
259    **-f-** or equivalent is given, bc(1) will give a fatal error and exit.
260
261    This is a **non-portable extension**.
262
263All long options are **non-portable extensions**.
264
265# STDIN
266
267If no files or expressions are given by the **-f**, **-\-file**, **-e**, or
268**-\-expression** options, then bc(1) read from **stdin**.
269
270However, there are a few caveats to this.
271
272First, **stdin** is evaluated a line at a time. The only exception to this is if
273the parse cannot complete. That means that starting a string without ending it
274or starting a function, **if** statement, or loop without ending it will also
275cause bc(1) to not execute.
276
277Second, after an **if** statement, bc(1) doesn't know if an **else** statement
278will follow, so it will not execute until it knows there will not be an **else**
279statement.
280
281# STDOUT
282
283Any non-error output is written to **stdout**. In addition, if history (see the
284**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
285both are output to **stdout**.
286
287**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
288error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
289**stdout** is closed, as in **bc <file> >&-**, it will quit with an error. This
290is done so that bc(1) can report problems when **stdout** is redirected to a
291file.
292
293If there are scripts that depend on the behavior of other bc(1) implementations,
294it is recommended that those scripts be changed to redirect **stdout** to
295**/dev/null**.
296
297# STDERR
298
299Any error output is written to **stderr**.
300
301**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
302error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
303**stderr** is closed, as in **bc <file> 2>&-**, it will quit with an error. This
304is done so that bc(1) can exit with an error code when **stderr** is redirected
305to a file.
306
307If there are scripts that depend on the behavior of other bc(1) implementations,
308it is recommended that those scripts be changed to redirect **stderr** to
309**/dev/null**.
310
311# SYNTAX
312
313The syntax for bc(1) programs is mostly C-like, with some differences. This
314bc(1) follows the [POSIX standard][1], which is a much more thorough resource
315for the language this bc(1) accepts. This section is meant to be a summary and a
316listing of all the extensions to the standard.
317
318In the sections below, **E** means expression, **S** means statement, and **I**
319means identifier.
320
321Identifiers (**I**) start with a lowercase letter and can be followed by any
322number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
323(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
324Identifiers with more than one character (letter) are a
325**non-portable extension**.
326
327**ibase** is a global variable determining how to interpret constant numbers. It
328is the "input" base, or the number base used for interpreting input numbers.
329**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
330(**-\-warn**) flags were not given on the command line, the max allowable value
331for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
332**ibase** is **2**. The max allowable value for **ibase** can be queried in
333bc(1) programs with the **maxibase()** built-in function.
334
335**obase** is a global variable determining how to output results. It is the
336"output" base, or the number base used for outputting numbers. **obase** is
337initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
338can be queried in bc(1) programs with the **maxobase()** built-in function. The
339min allowable value for **obase** is **2**. Values are output in the specified
340base.
341
342The *scale* of an expression is the number of digits in the result of the
343expression right of the decimal point, and **scale** is a global variable that
344sets the precision of any operations, with exceptions. **scale** is initially
345**0**. **scale** cannot be negative. The max allowable value for **scale** is
346**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
347built-in function.
348
349bc(1) has both *global* variables and *local* variables. All *local*
350variables are local to the function; they are parameters or are introduced in
351the **auto** list of a function (see the **FUNCTIONS** section). If a variable
352is accessed which is not a parameter or in the **auto** list, it is assumed to
353be *global*. If a parent function has a *local* variable version of a variable
354that a child function considers *global*, the value of that *global* variable in
355the child function is the value of the variable in the parent function, not the
356value of the actual *global* variable.
357
358All of the above applies to arrays as well.
359
360The value of a statement that is an expression (i.e., any of the named
361expressions or operands) is printed unless the lowest precedence operator is an
362assignment operator *and* the expression is notsurrounded by parentheses.
363
364The value that is printed is also assigned to the special variable **last**. A
365single dot (**.**) may also be used as a synonym for **last**. These are
366**non-portable extensions**.
367
368Either semicolons or newlines may separate statements.
369
370## Comments
371
372There are two kinds of comments:
373
3741.	Block comments are enclosed in **/\*** and **\*/**.
3752.	Line comments go from **#** until, and not including, the next newline. This
376	is a **non-portable extension**.
377
378## Named Expressions
379
380The following are named expressions in bc(1):
381
3821.	Variables: **I**
3832.	Array Elements: **I[E]**
3843.	**ibase**
3854.	**obase**
3865.	**scale**
3876.	**last** or a single dot (**.**)
388
389Number 6 is a **non-portable extension**.
390
391Variables and arrays do not interfere; users can have arrays named the same as
392variables. This also applies to functions (see the **FUNCTIONS** section), so a
393user can have a variable, array, and function that all have the same name, and
394they will not shadow each other, whether inside of functions or not.
395
396Named expressions are required as the operand of **increment**/**decrement**
397operators  and as the left side of **assignment** operators (see the *Operators*
398subsection).
399
400## Operands
401
402The following are valid operands in bc(1):
403
4041.	Numbers (see the *Numbers* subsection below).
4052.	Array indices (**I[E]**).
4063.	**(E)**: The value of **E** (used to change precedence).
4074.	**sqrt(E)**: The square root of **E**. **E** must be non-negative.
4085.	**length(E)**: The number of significant decimal digits in **E**. Returns
409	**1** for **0** with no decimal places. If given a string, the length of the
410	string is returned. Passing a string to **length(E)** is a **non-portable
411	extension**.
4126.	**length(I[])**: The number of elements in the array **I**. This is a
413	**non-portable extension**.
4147.	**scale(E)**: The *scale* of **E**.
4158.	**abs(E)**: The absolute value of **E**. This is a **non-portable
416	extension**.
4179.	**modexp(E, E, E)**: Modular exponentiation, where the first expression is
418	the base, the second is the exponent, and the third is the modulus. All
419	three values must be integers. The second argument must be non-negative. The
420	third argument must be non-zero. This is a **non-portable extension**.
42110.	**divmod(E, E, I[])**: Division and modulus in one operation. This is for
422	optimization. The first expression is the dividend, and the second is the
423	divisor, which must be non-zero. The return value is the quotient, and the
424	modulus is stored in index **0** of the provided array (the last argument).
425	This is a **non-portable extension**.
42611.	**asciify(E)**: If **E** is a string, returns a string that is the first
427	letter of its argument. If it is a number, calculates the number mod **256**
428	and returns that number as a one-character string. This is a **non-portable
429	extension**.
43012.	**I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
431	a non-**void** function (see the *Void Functions* subsection of the
432	**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
433	**I[]**, which will automatically be turned into array references (see the
434	*Array References* subsection of the **FUNCTIONS** section) if the
435	corresponding parameter in the function definition is an array reference.
43613.	**read()**: Reads a line from **stdin** and uses that as an expression. The
437	result of that expression is the result of the **read()** operand. This is a
438	**non-portable extension**.
43914.	**maxibase()**: The max allowable **ibase**. This is a **non-portable
440	extension**.
44115.	**maxobase()**: The max allowable **obase**. This is a **non-portable
442	extension**.
44316.	**maxscale()**: The max allowable **scale**. This is a **non-portable
444	extension**.
445
446## Numbers
447
448Numbers are strings made up of digits, uppercase letters, and at most **1**
449period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
450letters are equal to **9** + their position in the alphabet (i.e., **A** equals
451**10**, or **9+1**). If a digit or letter makes no sense with the current value
452of **ibase**, they are set to the value of the highest valid digit in **ibase**.
453
454Single-character numbers (i.e., **A** alone) take the value that they would have
455if they were valid digits, regardless of the value of **ibase**. This means that
456**A** alone always equals decimal **10** and **Z** alone always equals decimal
457**35**.
458
459## Operators
460
461The following arithmetic and logical operators can be used. They are listed in
462order of decreasing precedence. Operators in the same group have the same
463precedence.
464
465**++** **-\-**
466
467:   Type: Prefix and Postfix
468
469    Associativity: None
470
471    Description: **increment**, **decrement**
472
473**-** **!**
474
475:   Type: Prefix
476
477    Associativity: None
478
479    Description: **negation**, **boolean not**
480
481**\^**
482
483:   Type: Binary
484
485    Associativity: Right
486
487    Description: **power**
488
489**\*** **/** **%**
490
491:   Type: Binary
492
493    Associativity: Left
494
495    Description: **multiply**, **divide**, **modulus**
496
497**+** **-**
498
499:   Type: Binary
500
501    Associativity: Left
502
503    Description: **add**, **subtract**
504
505**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
506
507:   Type: Binary
508
509    Associativity: Right
510
511    Description: **assignment**
512
513**==** **\<=** **\>=** **!=** **\<** **\>**
514
515:   Type: Binary
516
517    Associativity: Left
518
519    Description: **relational**
520
521**&&**
522
523:   Type: Binary
524
525    Associativity: Left
526
527    Description: **boolean and**
528
529**||**
530
531:   Type: Binary
532
533    Associativity: Left
534
535    Description: **boolean or**
536
537The operators will be described in more detail below.
538
539**++** **-\-**
540
541:   The prefix and postfix **increment** and **decrement** operators behave
542    exactly like they would in C. They require a named expression (see the
543    *Named Expressions* subsection) as an operand.
544
545    The prefix versions of these operators are more efficient; use them where
546    possible.
547
548**-**
549
550:   The **negation** operator returns **0** if a user attempts to negate any
551    expression with the value **0**. Otherwise, a copy of the expression with
552    its sign flipped is returned.
553
554**!**
555
556:   The **boolean not** operator returns **1** if the expression is **0**, or
557    **0** otherwise.
558
559    This is a **non-portable extension**.
560
561**\^**
562
563:   The **power** operator (not the **exclusive or** operator, as it would be in
564    C) takes two expressions and raises the first to the power of the value of
565    the second. The *scale* of the result is equal to **scale**.
566
567    The second expression must be an integer (no *scale*), and if it is
568    negative, the first value must be non-zero.
569
570**\***
571
572:   The **multiply** operator takes two expressions, multiplies them, and
573    returns the product. If **a** is the *scale* of the first expression and
574    **b** is the *scale* of the second expression, the *scale* of the result is
575    equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
576    the obvious values.
577
578**/**
579
580:   The **divide** operator takes two expressions, divides them, and returns the
581    quotient. The *scale* of the result shall be the value of **scale**.
582
583    The second expression must be non-zero.
584
585**%**
586
587:   The **modulus** operator takes two expressions, **a** and **b**, and
588    evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
589    result of step 1 to calculate **a-(a/b)\*b** to *scale*
590    **max(scale+scale(b),scale(a))**.
591
592    The second expression must be non-zero.
593
594**+**
595
596:   The **add** operator takes two expressions, **a** and **b**, and returns the
597    sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
598
599**-**
600
601:   The **subtract** operator takes two expressions, **a** and **b**, and
602    returns the difference, with a *scale* equal to the max of the *scale*s of
603    **a** and **b**.
604
605**=** **+=** **-=** **\*=** **/=** **%=** **\^=**
606
607:   The **assignment** operators take two expressions, **a** and **b** where
608    **a** is a named expression (see the *Named Expressions* subsection).
609
610    For **=**, **b** is copied and the result is assigned to **a**. For all
611    others, **a** and **b** are applied as operands to the corresponding
612    arithmetic operator and the result is assigned to **a**.
613
614**==** **\<=** **\>=** **!=** **\<** **\>**
615
616:   The **relational** operators compare two expressions, **a** and **b**, and
617    if the relation holds, according to C language semantics, the result is
618    **1**. Otherwise, it is **0**.
619
620    Note that unlike in C, these operators have a lower precedence than the
621    **assignment** operators, which means that **a=b\>c** is interpreted as
622    **(a=b)\>c**.
623
624    Also, unlike the [standard][1] requires, these operators can appear anywhere
625    any other expressions can be used. This allowance is a
626    **non-portable extension**.
627
628**&&**
629
630:   The **boolean and** operator takes two expressions and returns **1** if both
631    expressions are non-zero, **0** otherwise.
632
633    This is *not* a short-circuit operator.
634
635    This is a **non-portable extension**.
636
637**||**
638
639:   The **boolean or** operator takes two expressions and returns **1** if one
640    of the expressions is non-zero, **0** otherwise.
641
642    This is *not* a short-circuit operator.
643
644    This is a **non-portable extension**.
645
646## Statements
647
648The following items are statements:
649
6501.	**E**
6512.	**{** **S** **;** ... **;** **S** **}**
6523.	**if** **(** **E** **)** **S**
6534.	**if** **(** **E** **)** **S** **else** **S**
6545.	**while** **(** **E** **)** **S**
6556.	**for** **(** **E** **;** **E** **;** **E** **)** **S**
6567.	An empty statement
6578.	**break**
6589.	**continue**
65910.	**quit**
66011.	**halt**
66112.	**limits**
66213.	A string of characters, enclosed in double quotes
66314.	**print** **E** **,** ... **,** **E**
66415.	**stream** **E** **,** ... **,** **E**
66516.	**I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
666	a **void** function (see the *Void Functions* subsection of the
667	**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
668	**I[]**, which will automatically be turned into array references (see the
669	*Array References* subsection of the **FUNCTIONS** section) if the
670	corresponding parameter in the function definition is an array reference.
671
672Numbers 4, 9, 11, 12, 14, 15, and 16 are **non-portable extensions**.
673
674Also, as a **non-portable extension**, any or all of the expressions in the
675header of a for loop may be omitted. If the condition (second expression) is
676omitted, it is assumed to be a constant **1**.
677
678The **break** statement causes a loop to stop iterating and resume execution
679immediately following a loop. This is only allowed in loops.
680
681The **continue** statement causes a loop iteration to stop early and returns to
682the start of the loop, including testing the loop condition. This is only
683allowed in loops.
684
685The **if** **else** statement does the same thing as in C.
686
687The **quit** statement causes bc(1) to quit, even if it is on a branch that will
688not be executed (it is a compile-time command).
689
690The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
691if it is on a branch of an **if** statement that is not executed, bc(1) does not
692quit.)
693
694The **limits** statement prints the limits that this bc(1) is subject to. This
695is like the **quit** statement in that it is a compile-time command.
696
697An expression by itself is evaluated and printed, followed by a newline.
698
699## Strings
700
701If strings appear as a statement by themselves, they are printed without a
702trailing newline.
703
704In addition to appearing as a lone statement by themselves, strings can be
705assigned to variables and array elements. They can also be passed to functions
706in variable parameters.
707
708If any statement that expects a string is given a variable that had a string
709assigned to it, the statement acts as though it had received a string.
710
711If any math operation is attempted on a string or a variable or array element
712that has been assigned a string, an error is raised, and bc(1) resets (see the
713**RESET** section).
714
715Assigning strings to variables and array elements and passing them to functions
716are **non-portable extensions**.
717
718## Print Statement
719
720The "expressions" in a **print** statement may also be strings. If they are, there
721are backslash escape sequences that are interpreted specially. What those
722sequences are, and what they cause to be printed, are shown below:
723
724**\\a**:   **\\a**
725
726**\\b**:   **\\b**
727
728**\\\\**:   **\\**
729
730**\\e**:   **\\**
731
732**\\f**:   **\\f**
733
734**\\n**:   **\\n**
735
736**\\q**:   **"**
737
738**\\r**:   **\\r**
739
740**\\t**:   **\\t**
741
742Any other character following a backslash causes the backslash and character to
743be printed as-is.
744
745Any non-string expression in a print statement shall be assigned to **last**,
746like any other expression that is printed.
747
748## Stream Statement
749
750The "expressions in a **stream** statement may also be strings.
751
752If a **stream** statement is given a string, it prints the string as though the
753string had appeared as its own statement. In other words, the **stream**
754statement prints strings normally, without a newline.
755
756If a **stream** statement is given a number, a copy of it is truncated and its
757absolute value is calculated. The result is then printed as though **obase** is
758**256** and each digit is interpreted as an 8-bit ASCII character, making it a
759byte stream.
760
761## Order of Evaluation
762
763All expressions in a statment are evaluated left to right, except as necessary
764to maintain order of operations. This means, for example, assuming that **i** is
765equal to **0**, in the expression
766
767    a[i++] = i++
768
769the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
770at the end of the expression.
771
772This includes function arguments. Thus, assuming **i** is equal to **0**, this
773means that in the expression
774
775    x(i++, i++)
776
777the first argument passed to **x()** is **0**, and the second argument is **1**,
778while **i** is equal to **2** before the function starts executing.
779
780# FUNCTIONS
781
782Function definitions are as follows:
783
784```
785define I(I,...,I){
786	auto I,...,I
787	S;...;S
788	return(E)
789}
790```
791
792Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
793make a parameter or **auto** var an array, and any **I** in the parameter list
794may be replaced with **\*I[]** to make a parameter an array reference. Callers
795of functions that take array references should not put an asterisk in the call;
796they must be called with just **I[]** like normal array parameters and will be
797automatically converted into references.
798
799As a **non-portable extension**, the opening brace of a **define** statement may
800appear on the next line.
801
802As a **non-portable extension**, the return statement may also be in one of the
803following forms:
804
8051.	**return**
8062.	**return** **(** **)**
8073.	**return** **E**
808
809The first two, or not specifying a **return** statement, is equivalent to
810**return (0)**, unless the function is a **void** function (see the *Void
811Functions* subsection below).
812
813## Void Functions
814
815Functions can also be **void** functions, defined as follows:
816
817```
818define void I(I,...,I){
819	auto I,...,I
820	S;...;S
821	return
822}
823```
824
825They can only be used as standalone expressions, where such an expression would
826be printed alone, except in a print statement.
827
828Void functions can only use the first two **return** statements listed above.
829They can also omit the return statement entirely.
830
831The word "void" is not treated as a keyword; it is still possible to have
832variables, arrays, and functions named **void**. The word "void" is only
833treated specially right after the **define** keyword.
834
835This is a **non-portable extension**.
836
837## Array References
838
839For any array in the parameter list, if the array is declared in the form
840
841```
842*I[]
843```
844
845it is a **reference**. Any changes to the array in the function are reflected,
846when the function returns, to the array that was passed in.
847
848Other than this, all function arguments are passed by value.
849
850This is a **non-portable extension**.
851
852# LIBRARY
853
854All of the functions below  are available when the **-l** or **-\-mathlib**
855command-line flags are given.
856
857## Standard Library
858
859The [standard][1] defines the following functions for the math library:
860
861**s(x)**
862
863:   Returns the sine of **x**, which is assumed to be in radians.
864
865    This is a transcendental function (see the *Transcendental Functions*
866    subsection below).
867
868**c(x)**
869
870:   Returns the cosine of **x**, which is assumed to be in radians.
871
872    This is a transcendental function (see the *Transcendental Functions*
873    subsection below).
874
875**a(x)**
876
877:   Returns the arctangent of **x**, in radians.
878
879    This is a transcendental function (see the *Transcendental Functions*
880    subsection below).
881
882**l(x)**
883
884:   Returns the natural logarithm of **x**.
885
886    This is a transcendental function (see the *Transcendental Functions*
887    subsection below).
888
889**e(x)**
890
891:   Returns the mathematical constant **e** raised to the power of **x**.
892
893    This is a transcendental function (see the *Transcendental Functions*
894    subsection below).
895
896**j(x, n)**
897
898:   Returns the bessel integer order **n** (truncated) of **x**.
899
900    This is a transcendental function (see the *Transcendental Functions*
901    subsection below).
902
903## Transcendental Functions
904
905All transcendental functions can return slightly inaccurate results (up to 1
906[ULP][4]). This is unavoidable, and [this article][5] explains why it is
907impossible and unnecessary to calculate exact results for the transcendental
908functions.
909
910Because of the possible inaccuracy, I recommend that users call those functions
911with the precision (**scale**) set to at least 1 higher than is necessary. If
912exact results are *absolutely* required, users can double the precision
913(**scale**) and then truncate.
914
915The transcendental functions in the standard math library are:
916
917* **s(x)**
918* **c(x)**
919* **a(x)**
920* **l(x)**
921* **e(x)**
922* **j(x, n)**
923
924# RESET
925
926When bc(1) encounters an error or a signal that it has a non-default handler
927for, it resets. This means that several things happen.
928
929First, any functions that are executing are stopped and popped off the stack.
930The behavior is not unlike that of exceptions in programming languages. Then
931the execution point is set so that any code waiting to execute (after all
932functions returned) is skipped.
933
934Thus, when bc(1) resets, it skips any remaining code waiting to be executed.
935Then, if it is interactive mode, and the error was not a fatal error (see the
936**EXIT STATUS** section), it asks for more input; otherwise, it exits with the
937appropriate return code.
938
939Note that this reset behavior is different from the GNU bc(1), which attempts to
940start executing the statement right after the one that caused an error.
941
942# PERFORMANCE
943
944Most bc(1) implementations use **char** types to calculate the value of **1**
945decimal digit at a time, but that can be slow. This bc(1) does something
946different.
947
948It uses large integers to calculate more than **1** decimal digit at a time. If
949built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
950**64**, then each integer has **9** decimal digits. If built in an environment
951where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
952value (the number of decimal digits per large integer) is called
953**BC_BASE_DIGS**.
954
955The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
956the **limits** statement.
957
958In addition, this bc(1) uses an even larger integer for overflow checking. This
959integer type depends on the value of **BC_LONG_BIT**, but is always at least
960twice as large as the integer type used to store digits.
961
962# LIMITS
963
964The following are the limits on bc(1):
965
966**BC_LONG_BIT**
967
968:   The number of bits in the **long** type in the environment where bc(1) was
969    built. This determines how many decimal digits can be stored in a single
970    large integer (see the **PERFORMANCE** section).
971
972**BC_BASE_DIGS**
973
974:   The number of decimal digits per large integer (see the **PERFORMANCE**
975    section). Depends on **BC_LONG_BIT**.
976
977**BC_BASE_POW**
978
979:   The max decimal number that each large integer can store (see
980    **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
981
982**BC_OVERFLOW_MAX**
983
984:   The max number that the overflow type (see the **PERFORMANCE** section) can
985    hold. Depends on **BC_LONG_BIT**.
986
987**BC_BASE_MAX**
988
989:   The maximum output base. Set at **BC_BASE_POW**.
990
991**BC_DIM_MAX**
992
993:   The maximum size of arrays. Set at **SIZE_MAX-1**.
994
995**BC_SCALE_MAX**
996
997:   The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
998
999**BC_STRING_MAX**
1000
1001:   The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
1002
1003**BC_NAME_MAX**
1004
1005:   The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
1006
1007**BC_NUM_MAX**
1008
1009:   The maximum length of a number (in decimal digits), which includes digits
1010    after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1011
1012Exponent
1013
1014:   The maximum allowable exponent (positive or negative). Set at
1015    **BC_OVERFLOW_MAX**.
1016
1017Number of vars
1018
1019:   The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
1020
1021The actual values can be queried with the **limits** statement.
1022
1023These limits are meant to be effectively non-existent; the limits are so large
1024(at least on 64-bit machines) that there should not be any point at which they
1025become a problem. In fact, memory should be exhausted before these limits should
1026be hit.
1027
1028# ENVIRONMENT VARIABLES
1029
1030bc(1) recognizes the following environment variables:
1031
1032**POSIXLY_CORRECT**
1033
1034:   If this variable exists (no matter the contents), bc(1) behaves as if
1035    the **-s** option was given.
1036
1037**BC_ENV_ARGS**
1038
1039:   This is another way to give command-line arguments to bc(1). They should be
1040    in the same format as all other command-line arguments. These are always
1041    processed first, so any files given in **BC_ENV_ARGS** will be processed
1042    before arguments and files given on the command-line. This gives the user
1043    the ability to set up "standard" options and files to be used at every
1044    invocation. The most useful thing for such files to contain would be useful
1045    functions that the user might want every time bc(1) runs.
1046
1047    The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
1048    but it does not understand escape sequences. For example, the string
1049    **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
1050    **"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
1051
1052    The quote parsing will handle either kind of quotes, **'** or **"**. Thus,
1053    if you have a file with any number of single quotes in the name, you can use
1054    double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice
1055    versa if you have a file with double quotes. However, handling a file with
1056    both kinds of quotes in **BC_ENV_ARGS** is not supported due to the
1057    complexity of the parsing, though such files are still supported on the
1058    command-line where the parsing is done by the shell.
1059
1060**BC_LINE_LENGTH**
1061
1062:   If this environment variable exists and contains an integer that is greater
1063    than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
1064    lines to that length, including the backslash (**\\**). The default line
1065    length is **70**.
1066
1067**BC_BANNER**
1068
1069:   If this environment variable exists and contains an integer, then a non-zero
1070    value activates the copyright banner when bc(1) is in interactive mode,
1071    while zero deactivates it.
1072
1073    If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
1074    then this environment variable has no effect because bc(1) does not print
1075    the banner when not in interactive mode.
1076
1077    This environment variable overrides the default, which can be queried with
1078    the **-h** or **-\-help** options.
1079
1080**BC_SIGINT_RESET**
1081
1082:   If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
1083    then this environment variable has no effect because bc(1) exits on
1084    **SIGINT** when not in interactive mode.
1085
1086    However, when bc(1) is in interactive mode, then if this environment
1087    variable exists and contains an integer, a non-zero value makes bc(1) reset
1088    on **SIGINT**, rather than exit, and zero makes bc(1) exit. If this
1089    environment variable exists and is *not* an integer, then bc(1) will exit on
1090    **SIGINT**.
1091
1092    This environment variable overrides the default, which can be queried with
1093    the **-h** or **-\-help** options.
1094
1095**BC_TTY_MODE**
1096
1097:   If TTY mode is *not* available (see the **TTY MODE** section), then this
1098    environment variable has no effect.
1099
1100    However, when TTY mode is available, then if this environment variable
1101    exists and contains an integer, then a non-zero value makes bc(1) use TTY
1102    mode, and zero makes bc(1) not use TTY mode.
1103
1104    This environment variable overrides the default, which can be queried with
1105    the **-h** or **-\-help** options.
1106
1107**BC_PROMPT**
1108
1109:   If TTY mode is *not* available (see the **TTY MODE** section), then this
1110    environment variable has no effect.
1111
1112    However, when TTY mode is available, then if this environment variable
1113    exists and contains an integer, a non-zero value makes bc(1) use a prompt,
1114    and zero or a non-integer makes bc(1) not use a prompt. If this environment
1115    variable does not exist and **BC_TTY_MODE** does, then the value of the
1116    **BC_TTY_MODE** environment variable is used.
1117
1118    This environment variable and the **BC_TTY_MODE** environment variable
1119    override the default, which can be queried with the **-h** or **-\-help**
1120    options.
1121
1122# EXIT STATUS
1123
1124bc(1) returns the following exit statuses:
1125
1126**0**
1127
1128:   No error.
1129
1130**1**
1131
1132:   A math error occurred. This follows standard practice of using **1** for
1133    expected errors, since math errors will happen in the process of normal
1134    execution.
1135
1136    Math errors include divide by **0**, taking the square root of a negative
1137    number, attempting to convert a negative number to a hardware integer,
1138    overflow when converting a number to a hardware integer, overflow when
1139    calculating the size of a number, and attempting to use a non-integer where
1140    an integer is required.
1141
1142    Converting to a hardware integer happens for the second operand of the power
1143    (**\^**) operator and the corresponding assignment operator.
1144
1145**2**
1146
1147:   A parse error occurred.
1148
1149    Parse errors include unexpected **EOF**, using an invalid character, failing
1150    to find the end of a string or comment, using a token where it is invalid,
1151    giving an invalid expression, giving an invalid print statement, giving an
1152    invalid function definition, attempting to assign to an expression that is
1153    not a named expression (see the *Named Expressions* subsection of the
1154    **SYNTAX** section), giving an invalid **auto** list, having a duplicate
1155    **auto**/function parameter, failing to find the end of a code block,
1156    attempting to return a value from a **void** function, attempting to use a
1157    variable as a reference, and using any extensions when the option **-s** or
1158    any equivalents were given.
1159
1160**3**
1161
1162:   A runtime error occurred.
1163
1164    Runtime errors include assigning an invalid number to any global (**ibase**,
1165    **obase**, or **scale**), giving a bad expression to a **read()** call,
1166    calling **read()** inside of a **read()** call, type errors, passing the
1167    wrong number of arguments to functions, attempting to call an undefined
1168    function, and attempting to use a **void** function call as a value in an
1169    expression.
1170
1171**4**
1172
1173:   A fatal error occurred.
1174
1175    Fatal errors include memory allocation errors, I/O errors, failing to open
1176    files, attempting to use files that do not have only ASCII characters (bc(1)
1177    only accepts ASCII characters), attempting to open a directory as a file,
1178    and giving invalid command-line options.
1179
1180The exit status **4** is special; when a fatal error occurs, bc(1) always exits
1181and returns **4**, no matter what mode bc(1) is in.
1182
1183The other statuses will only be returned when bc(1) is not in interactive mode
1184(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the
1185**RESET** section) and accepts more input when one of those errors occurs in
1186interactive mode. This is also the case when interactive mode is forced by the
1187**-i** flag or **-\-interactive** option.
1188
1189These exit statuses allow bc(1) to be used in shell scripting with error
1190checking, and its normal behavior can be forced by using the **-i** flag or
1191**-\-interactive** option.
1192
1193# INTERACTIVE MODE
1194
1195Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
1196Interactive mode is turned on automatically when both **stdin** and **stdout**
1197are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
1198turn it on in other situations.
1199
1200In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
1201section), and in normal execution, flushes **stdout** as soon as execution is
1202done for the current input. bc(1) may also reset on **SIGINT** instead of exit,
1203depending on the contents of, or default for, the **BC_SIGINT_RESET**
1204environment variable (see the **ENVIRONMENT VARIABLES** section).
1205
1206# TTY MODE
1207
1208If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
1209mode" is considered to be available, and thus, bc(1) can turn on TTY mode,
1210subject to some settings.
1211
1212If there is the environment variable **BC_TTY_MODE** in the environment (see the
1213**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
1214non-zero integer, bc(1) will turn on TTY mode when **stdin**, **stdout**, and
1215**stderr** are all connected to a TTY. If the **BC_TTY_MODE** environment
1216variable exists but is *not* a non-zero integer, then bc(1) will not turn TTY
1217mode on.
1218
1219If the environment variable **BC_TTY_MODE** does *not* exist, the default
1220setting is used. The default setting can be queried with the **-h** or
1221**-\-help** options.
1222
1223TTY mode is different from interactive mode because interactive mode is required
1224in the [bc(1) specification][1], and interactive mode requires only **stdin**
1225and **stdout** to be connected to a terminal.
1226
1227## Command-Line History
1228
1229Command-line history is only enabled if TTY mode is, i.e., that **stdin**,
1230**stdout**, and **stderr** are connected to a TTY and the **BC_TTY_MODE**
1231environment variable (see the **ENVIRONMENT VARIABLES** section) and its default
1232do not disable TTY mode. See the **COMMAND LINE HISTORY** section for more
1233information.
1234
1235## Prompt
1236
1237If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
1238can be turned on or off with an environment variable: **BC_PROMPT** (see the
1239**ENVIRONMENT VARIABLES** section).
1240
1241If the environment variable **BC_PROMPT** exists and is a non-zero integer, then
1242the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
1243to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
1244prompt will be turned on under the same conditions, except that the **-R** and
1245**-\-no-read-prompt** options must also not be used.
1246
1247However, if **BC_PROMPT** does not exist, the prompt can be enabled or disabled
1248with the **BC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
1249options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
1250VARIABLES** and **OPTIONS** sections for more details.
1251
1252# SIGNAL HANDLING
1253
1254Sending a **SIGINT** will cause bc(1) to do one of two things.
1255
1256If bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
1257the **BC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
1258section), or its default, is either not an integer or it is zero, bc(1) will
1259exit.
1260
1261However, if bc(1) is in interactive mode, and the **BC_SIGINT_RESET** or its
1262default is an integer and non-zero, then bc(1) will stop executing the current
1263input and reset (see the **RESET** section) upon receiving a **SIGINT**.
1264
1265Note that "current input" can mean one of two things. If bc(1) is processing
1266input from **stdin** in interactive mode, it will ask for more input. If bc(1)
1267is processing input from a file in interactive mode, it will stop processing the
1268file and start processing the next file, if one exists, or ask for input from
1269**stdin** if no other file exists.
1270
1271This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
1272can seem as though bc(1) did not respond to the signal since it will immediately
1273start executing the next file. This is by design; most files that users execute
1274when interacting with bc(1) have function definitions, which are quick to parse.
1275If a file takes a long time to execute, there may be a bug in that file. The
1276rest of the files could still be executed without problem, allowing the user to
1277continue.
1278
1279**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
1280default handler for all other signals. The one exception is **SIGHUP**; in that
1281case, and only when bc(1) is in TTY mode (see the **TTY MODE** section), a
1282**SIGHUP** will cause bc(1) to clean up and exit.
1283
1284# COMMAND LINE HISTORY
1285
1286bc(1) supports interactive command-line editing.
1287
1288If bc(1) can be in TTY mode (see the **TTY MODE** section), history can be
1289enabled. This means that command-line history can only be enabled when
1290**stdin**, **stdout**, and **stderr** are all connected to a TTY.
1291
1292Like TTY mode itself, it can be turned on or off with the environment variable
1293**BC_TTY_MODE** (see the **ENVIRONMENT VARIABLES** section).
1294
1295If history is enabled, previous lines can be recalled and edited with the arrow
1296keys.
1297
1298**Note**: tabs are converted to 8 spaces.
1299
1300# LOCALES
1301
1302This bc(1) ships with support for adding error messages for different locales
1303and thus, supports **LC_MESSAGES**.
1304
1305# SEE ALSO
1306
1307dc(1)
1308
1309# STANDARDS
1310
1311bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
1312specification. The flags **-efghiqsvVw**, all long options, and the extensions
1313noted above are extensions to that specification.
1314
1315Note that the specification explicitly says that bc(1) only accepts numbers that
1316use a period (**.**) as a radix point, regardless of the value of
1317**LC_NUMERIC**.
1318
1319This bc(1) supports error messages for different locales, and thus, it supports
1320**LC_MESSAGES**.
1321
1322# BUGS
1323
1324None are known. Report bugs at https://git.yzena.com/gavin/bc.
1325
1326# AUTHORS
1327
1328Gavin D. Howard <gavin@yzena.com> and contributors.
1329
1330[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
1331[2]: https://www.gnu.org/software/bc/
1332[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
1333[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
1334[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
1335[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
1336