xref: /freebsd/contrib/bc/manuals/bc/H.1.md (revision 16038816)
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
49# OPTIONS
50
51The following are the options that bc(1) accepts.
52
53**-g**, **-\-global-stacks**
54
55:   Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks.
56
57    This has the effect that a copy of the current value of all four are pushed
58    onto a stack for every function call, as well as popped when every function
59    returns. This means that functions can assign to any and all of those
60    globals without worrying that the change will affect other functions.
61    Thus, a hypothetical function named **output(x,b)** that simply printed
62    **x** in base **b** could be written like this:
63
64        define void output(x, b) {
65            obase=b
66            x
67        }
68
69    instead of like this:
70
71        define void output(x, b) {
72            auto c
73            c=obase
74            obase=b
75            x
76            obase=c
77        }
78
79    This makes writing functions much easier.
80
81    (**Note**: the function **output(x,b)** exists in the extended math library.
82     See the **LIBRARY** section.)
83
84    However, since using this flag means that functions cannot set **ibase**,
85    **obase**, **scale**, or **seed** globally, functions that are made to do so
86    cannot work anymore. There are two possible use cases for that, and each has
87    a 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**,
97    **scale**, or **seed** globally for any other purpose, it could be split
98    into one to four functions (based on how many globals it sets) and each of
99    those functions could return the desired value for a global.
100
101    For functions that set **seed**, the value assigned to **seed** is not
102    propagated to parent functions. This means that the sequence of
103    pseudo-random numbers that they see will not be the same sequence of
104    pseudo-random numbers that any parent sees. This is only the case once
105    **seed** has been set.
106
107    If a function desires to not affect the sequence of pseudo-random numbers
108    of its parents, but wants to use the same **seed**, it can use the following
109    line:
110
111        seed = seed
112
113    If the behavior of this option is desired for every run of bc(1), then users
114    could make sure to define **BC_ENV_ARGS** and include this option (see the
115    **ENVIRONMENT VARIABLES** section for more details).
116
117    If **-s**, **-w**, or any equivalents are used, this option is ignored.
118
119    This is a **non-portable extension**.
120
121**-h**, **-\-help**
122
123:   Prints a usage message and quits.
124
125**-i**, **-\-interactive**
126
127:   Forces interactive mode. (See the **INTERACTIVE MODE** section.)
128
129    This is a **non-portable extension**.
130
131**-l**, **-\-mathlib**
132
133:   Sets **scale** (see the **SYNTAX** section) to **20** and loads the included
134    math library and the extended math library before running any code,
135    including any expressions or files specified on the command line.
136
137    To learn what is in the libraries, see the **LIBRARY** section.
138
139**-P**, **-\-no-prompt**
140
141:   Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
142    See the **TTY MODE** section.) This is mostly for those users that do not
143    want a prompt or are not used to having them in bc(1). Most of those users
144    would want to put this option in **BC_ENV_ARGS** (see the
145    **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    This is a **non-portable extension**.
162
163**-q**, **-\-quiet**
164
165:   This option is for compatibility with the [GNU bc(1)][2]; it is a no-op.
166    Without this option, GNU bc(1) prints a copyright header. This bc(1) only
167    prints the copyright header if one or more of the **-v**, **-V**, or
168    **-\-version** options are given.
169
170    This is a **non-portable extension**.
171
172**-s**, **-\-standard**
173
174:   Process exactly the language defined by the [standard][1] and error if any
175    extensions are used.
176
177    This is a **non-portable extension**.
178
179**-v**, **-V**, **-\-version**
180
181:   Print the version information (copyright header) and exit.
182
183    This is a **non-portable extension**.
184
185**-w**, **-\-warn**
186
187:   Like **-s** and **-\-standard**, except that warnings (and not errors) are
188    printed for non-standard extensions and execution continues normally.
189
190    This is a **non-portable extension**.
191
192**-e** *expr*, **-\-expression**=*expr*
193
194:   Evaluates *expr*. If multiple expressions are given, they are evaluated in
195    order. If files are given as well (see below), the expressions and files are
196    evaluated in the order given. This means that if a file is given before an
197    expression, the file is read in and evaluated first.
198
199    If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
200    see the **ENVIRONMENT VARIABLES** section), then after processing all
201    expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
202    as an argument at least once to **-f** or **-\-file**, whether on the
203    command-line or in **BC_ENV_ARGS**. However, if any other **-e**,
204    **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
205    or equivalent is given, bc(1) will give a fatal error and exit.
206
207    This is a **non-portable extension**.
208
209**-f** *file*, **-\-file**=*file*
210
211:   Reads in *file* and evaluates it, line by line, as though it were read
212    through **stdin**. If expressions are also given (see above), the
213    expressions are evaluated in the order given.
214
215    If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**,
216    see the **ENVIRONMENT VARIABLES** section), then after processing all
217    expressions and files, bc(1) will exit, unless **-** (**stdin**) was given
218    as an argument at least once to **-f** or **-\-file**. However, if any other
219    **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
220    **-f-** or equivalent is given, bc(1) will give a fatal error and exit.
221
222    This is a **non-portable extension**.
223
224All long options are **non-portable extensions**.
225
226# STDOUT
227
228Any non-error output is written to **stdout**. In addition, if history (see the
229**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
230both are output to **stdout**.
231
232**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
233error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
234**stdout** is closed, as in **bc <file> >&-**, it will quit with an error. This
235is done so that bc(1) can report problems when **stdout** is redirected to a
236file.
237
238If there are scripts that depend on the behavior of other bc(1) implementations,
239it is recommended that those scripts be changed to redirect **stdout** to
240**/dev/null**.
241
242# STDERR
243
244Any error output is written to **stderr**.
245
246**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal
247error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
248**stderr** is closed, as in **bc <file> 2>&-**, it will quit with an error. This
249is done so that bc(1) can exit with an error code when **stderr** is redirected
250to a file.
251
252If there are scripts that depend on the behavior of other bc(1) implementations,
253it is recommended that those scripts be changed to redirect **stderr** to
254**/dev/null**.
255
256# SYNTAX
257
258The syntax for bc(1) programs is mostly C-like, with some differences. This
259bc(1) follows the [POSIX standard][1], which is a much more thorough resource
260for the language this bc(1) accepts. This section is meant to be a summary and a
261listing of all the extensions to the standard.
262
263In the sections below, **E** means expression, **S** means statement, and **I**
264means identifier.
265
266Identifiers (**I**) start with a lowercase letter and can be followed by any
267number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits
268(**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***.
269Identifiers with more than one character (letter) are a
270**non-portable extension**.
271
272**ibase** is a global variable determining how to interpret constant numbers. It
273is the "input" base, or the number base used for interpreting input numbers.
274**ibase** is initially **10**. If the **-s** (**-\-standard**) and **-w**
275(**-\-warn**) flags were not given on the command line, the max allowable value
276for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for
277**ibase** is **2**. The max allowable value for **ibase** can be queried in
278bc(1) programs with the **maxibase()** built-in function.
279
280**obase** is a global variable determining how to output results. It is the
281"output" base, or the number base used for outputting numbers. **obase** is
282initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and
283can be queried in bc(1) programs with the **maxobase()** built-in function. The
284min allowable value for **obase** is **0**. If **obase** is **0**, values are
285output in scientific notation, and if **obase** is **1**, values are output in
286engineering notation. Otherwise, values are output in the specified base.
287
288Outputting in scientific and engineering notations are **non-portable
289extensions**.
290
291The *scale* of an expression is the number of digits in the result of the
292expression right of the decimal point, and **scale** is a global variable that
293sets the precision of any operations, with exceptions. **scale** is initially
294**0**. **scale** cannot be negative. The max allowable value for **scale** is
295**BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()**
296built-in function.
297
298bc(1) has both *global* variables and *local* variables. All *local*
299variables are local to the function; they are parameters or are introduced in
300the **auto** list of a function (see the **FUNCTIONS** section). If a variable
301is accessed which is not a parameter or in the **auto** list, it is assumed to
302be *global*. If a parent function has a *local* variable version of a variable
303that a child function considers *global*, the value of that *global* variable in
304the child function is the value of the variable in the parent function, not the
305value of the actual *global* variable.
306
307All of the above applies to arrays as well.
308
309The value of a statement that is an expression (i.e., any of the named
310expressions or operands) is printed unless the lowest precedence operator is an
311assignment operator *and* the expression is notsurrounded by parentheses.
312
313The value that is printed is also assigned to the special variable **last**. A
314single dot (**.**) may also be used as a synonym for **last**. These are
315**non-portable extensions**.
316
317Either semicolons or newlines may separate statements.
318
319## Comments
320
321There are two kinds of comments:
322
3231.	Block comments are enclosed in **/\*** and **\*/**.
3242.	Line comments go from **#** until, and not including, the next newline. This
325	is a **non-portable extension**.
326
327## Named Expressions
328
329The following are named expressions in bc(1):
330
3311.	Variables: **I**
3322.	Array Elements: **I[E]**
3333.	**ibase**
3344.	**obase**
3355.	**scale**
3366.	**seed**
3377.	**last** or a single dot (**.**)
338
339Numbers 6 and 7 are **non-portable extensions**.
340
341The meaning of **seed** is dependent on the current pseudo-random number
342generator but is guaranteed to not change except for new major versions.
343
344The *scale* and sign of the value may be significant.
345
346If a previously used **seed** value is assigned to **seed** and used again, the
347pseudo-random number generator is guaranteed to produce the same sequence of
348pseudo-random numbers as it did when the **seed** value was previously used.
349
350The exact value assigned to **seed** is not guaranteed to be returned if
351**seed** is queried again immediately. However, if **seed** *does* return a
352different value, both values, when assigned to **seed**, are guaranteed to
353produce the same sequence of pseudo-random numbers. This means that certain
354values assigned to **seed** will *not* produce unique sequences of pseudo-random
355numbers. The value of **seed** will change after any use of the **rand()** and
356**irand(E)** operands (see the *Operands* subsection below), except if the
357parameter passed to **irand(E)** is **0**, **1**, or negative.
358
359There is no limit to the length (number of significant decimal digits) or
360*scale* of the value that can be assigned to **seed**.
361
362Variables and arrays do not interfere; users can have arrays named the same as
363variables. This also applies to functions (see the **FUNCTIONS** section), so a
364user can have a variable, array, and function that all have the same name, and
365they will not shadow each other, whether inside of functions or not.
366
367Named expressions are required as the operand of **increment**/**decrement**
368operators  and as the left side of **assignment** operators (see the *Operators*
369subsection).
370
371## Operands
372
373The following are valid operands in bc(1):
374
3751.	Numbers (see the *Numbers* subsection below).
3762.	Array indices (**I[E]**).
3773.	**(E)**: The value of **E** (used to change precedence).
3784.	**sqrt(E)**: The square root of **E**. **E** must be non-negative.
3795.	**length(E)**: The number of significant decimal digits in **E**.
3806.	**length(I[])**: The number of elements in the array **I**. This is a
381	**non-portable extension**.
3827.	**scale(E)**: The *scale* of **E**.
3838.	**abs(E)**: The absolute value of **E**. This is a **non-portable
384	extension**.
3859.	**I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
386	a non-**void** function (see the *Void Functions* subsection of the
387	**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
388	**I[]**, which will automatically be turned into array references (see the
389	*Array References* subsection of the **FUNCTIONS** section) if the
390	corresponding parameter in the function definition is an array reference.
39110.	**read()**: Reads a line from **stdin** and uses that as an expression. The
392	result of that expression is the result of the **read()** operand. This is a
393	**non-portable extension**.
39411.	**maxibase()**: The max allowable **ibase**. This is a **non-portable
395	extension**.
39612.	**maxobase()**: The max allowable **obase**. This is a **non-portable
397	extension**.
39813.	**maxscale()**: The max allowable **scale**. This is a **non-portable
399	extension**.
40014.	**rand()**: A pseudo-random integer between **0** (inclusive) and
401	**BC_RAND_MAX** (inclusive). Using this operand will change the value of
402	**seed**. This is a **non-portable extension**.
40315.	**irand(E)**: A pseudo-random integer between **0** (inclusive) and the
404	value of **E** (exclusive). If **E** is negative or is a non-integer
405	(**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see
406	the **RESET** section) while **seed** remains unchanged. If **E** is larger
407	than **BC_RAND_MAX**, the higher bound is honored by generating several
408	pseudo-random integers, multiplying them by appropriate powers of
409	**BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that
410	can be generated with this operand is unbounded. Using this operand will
411	change the value of **seed**, unless the value of **E** is **0** or **1**.
412	In that case, **0** is returned, and **seed** is *not* changed. This is a
413	**non-portable extension**.
41416.	**maxrand()**: The max integer returned by **rand()**. This is a
415	**non-portable extension**.
416
417The integers generated by **rand()** and **irand(E)** are guaranteed to be as
418unbiased as possible, subject to the limitations of the pseudo-random number
419generator.
420
421**Note**: The values returned by the pseudo-random number generator with
422**rand()** and **irand(E)** are guaranteed to *NOT* be cryptographically secure.
423This is a consequence of using a seeded pseudo-random number generator. However,
424they *are* guaranteed to be reproducible with identical **seed** values. This
425means that the pseudo-random values from bc(1) should only be used where a
426reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
427use a non-seeded pseudo-random number generator.
428
429## Numbers
430
431Numbers are strings made up of digits, uppercase letters, and at most **1**
432period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase
433letters are equal to **9** + their position in the alphabet (i.e., **A** equals
434**10**, or **9+1**). If a digit or letter makes no sense with the current value
435of **ibase**, they are set to the value of the highest valid digit in **ibase**.
436
437Single-character numbers (i.e., **A** alone) take the value that they would have
438if they were valid digits, regardless of the value of **ibase**. This means that
439**A** alone always equals decimal **10** and **Z** alone always equals decimal
440**35**.
441
442In addition, bc(1) accepts numbers in scientific notation. These have the form
443**\<number\>e\<integer\>**. The exponent (the portion after the **e**) must be
444an integer. An example is **1.89237e9**, which is equal to **1892370000**.
445Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**.
446
447Using scientific notation is an error or warning if the **-s** or **-w**,
448respectively, command-line options (or equivalents) are given.
449
450**WARNING**: Both the number and the exponent in scientific notation are
451interpreted according to the current **ibase**, but the number is still
452multiplied by **10\^exponent** regardless of the current **ibase**. For example,
453if **ibase** is **16** and bc(1) is given the number string **FFeA**, the
454resulting decimal number will be **2550000000000**, and if bc(1) is given the
455number string **10e-4**, the resulting decimal number will be **0.0016**.
456
457Accepting input as scientific notation is a **non-portable extension**.
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: Postfix
484
485    Associativity: None
486
487    Description: **truncation**
488
489**\@**
490
491:   Type: Binary
492
493    Associativity: Right
494
495    Description: **set precision**
496
497**\^**
498
499:   Type: Binary
500
501    Associativity: Right
502
503    Description: **power**
504
505**\*** **/** **%**
506
507:   Type: Binary
508
509    Associativity: Left
510
511    Description: **multiply**, **divide**, **modulus**
512
513**+** **-**
514
515:   Type: Binary
516
517    Associativity: Left
518
519    Description: **add**, **subtract**
520
521**\<\<** **\>\>**
522
523:   Type: Binary
524
525    Associativity: Left
526
527    Description: **shift left**, **shift right**
528
529**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
530
531:   Type: Binary
532
533    Associativity: Right
534
535    Description: **assignment**
536
537**==** **\<=** **\>=** **!=** **\<** **\>**
538
539:   Type: Binary
540
541    Associativity: Left
542
543    Description: **relational**
544
545**&&**
546
547:   Type: Binary
548
549    Associativity: Left
550
551    Description: **boolean and**
552
553**||**
554
555:   Type: Binary
556
557    Associativity: Left
558
559    Description: **boolean or**
560
561The operators will be described in more detail below.
562
563**++** **-\-**
564
565:   The prefix and postfix **increment** and **decrement** operators behave
566    exactly like they would in C. They require a named expression (see the
567    *Named Expressions* subsection) as an operand.
568
569    The prefix versions of these operators are more efficient; use them where
570    possible.
571
572**-**
573
574:   The **negation** operator returns **0** if a user attempts to negate any
575    expression with the value **0**. Otherwise, a copy of the expression with
576    its sign flipped is returned.
577
578**!**
579
580:   The **boolean not** operator returns **1** if the expression is **0**, or
581    **0** otherwise.
582
583    This is a **non-portable extension**.
584
585**\$**
586
587:   The **truncation** operator returns a copy of the given expression with all
588    of its *scale* removed.
589
590    This is a **non-portable extension**.
591
592**\@**
593
594:   The **set precision** operator takes two expressions and returns a copy of
595    the first with its *scale* equal to the value of the second expression. That
596    could either mean that the number is returned without change (if the
597    *scale* of the first expression matches the value of the second
598    expression), extended (if it is less), or truncated (if it is more).
599
600    The second expression must be an integer (no *scale*) and non-negative.
601
602    This is a **non-portable extension**.
603
604**\^**
605
606:   The **power** operator (not the **exclusive or** operator, as it would be in
607    C) takes two expressions and raises the first to the power of the value of
608    the second. The *scale* of the result is equal to **scale**.
609
610    The second expression must be an integer (no *scale*), and if it is
611    negative, the first value must be non-zero.
612
613**\***
614
615:   The **multiply** operator takes two expressions, multiplies them, and
616    returns the product. If **a** is the *scale* of the first expression and
617    **b** is the *scale* of the second expression, the *scale* of the result is
618    equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
619    the obvious values.
620
621**/**
622
623:   The **divide** operator takes two expressions, divides them, and returns the
624    quotient. The *scale* of the result shall be the value of **scale**.
625
626    The second expression must be non-zero.
627
628**%**
629
630:   The **modulus** operator takes two expressions, **a** and **b**, and
631    evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the
632    result of step 1 to calculate **a-(a/b)\*b** to *scale*
633    **max(scale+scale(b),scale(a))**.
634
635    The second expression must be non-zero.
636
637**+**
638
639:   The **add** operator takes two expressions, **a** and **b**, and returns the
640    sum, with a *scale* equal to the max of the *scale*s of **a** and **b**.
641
642**-**
643
644:   The **subtract** operator takes two expressions, **a** and **b**, and
645    returns the difference, with a *scale* equal to the max of the *scale*s of
646    **a** and **b**.
647
648**\<\<**
649
650:   The **left shift** operator takes two expressions, **a** and **b**, and
651    returns a copy of the value of **a** with its decimal point moved **b**
652    places to the right.
653
654    The second expression must be an integer (no *scale*) and non-negative.
655
656    This is a **non-portable extension**.
657
658**\>\>**
659
660:   The **right shift** operator takes two expressions, **a** and **b**, and
661    returns a copy of the value of **a** with its decimal point moved **b**
662    places to the left.
663
664    The second expression must be an integer (no *scale*) and non-negative.
665
666    This is a **non-portable extension**.
667
668**=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=**
669
670:   The **assignment** operators take two expressions, **a** and **b** where
671    **a** is a named expression (see the *Named Expressions* subsection).
672
673    For **=**, **b** is copied and the result is assigned to **a**. For all
674    others, **a** and **b** are applied as operands to the corresponding
675    arithmetic operator and the result is assigned to **a**.
676
677    The **assignment** operators that correspond to operators that are
678    extensions are themselves **non-portable extensions**.
679
680**==** **\<=** **\>=** **!=** **\<** **\>**
681
682:   The **relational** operators compare two expressions, **a** and **b**, and
683    if the relation holds, according to C language semantics, the result is
684    **1**. Otherwise, it is **0**.
685
686    Note that unlike in C, these operators have a lower precedence than the
687    **assignment** operators, which means that **a=b\>c** is interpreted as
688    **(a=b)\>c**.
689
690    Also, unlike the [standard][1] requires, these operators can appear anywhere
691    any other expressions can be used. This allowance is a
692    **non-portable extension**.
693
694**&&**
695
696:   The **boolean and** operator takes two expressions and returns **1** if both
697    expressions are non-zero, **0** otherwise.
698
699    This is *not* a short-circuit operator.
700
701    This is a **non-portable extension**.
702
703**||**
704
705:   The **boolean or** operator takes two expressions and returns **1** if one
706    of the expressions is non-zero, **0** otherwise.
707
708    This is *not* a short-circuit operator.
709
710    This is a **non-portable extension**.
711
712## Statements
713
714The following items are statements:
715
7161.	**E**
7172.	**{** **S** **;** ... **;** **S** **}**
7183.	**if** **(** **E** **)** **S**
7194.	**if** **(** **E** **)** **S** **else** **S**
7205.	**while** **(** **E** **)** **S**
7216.	**for** **(** **E** **;** **E** **;** **E** **)** **S**
7227.	An empty statement
7238.	**break**
7249.	**continue**
72510.	**quit**
72611.	**halt**
72712.	**limits**
72813.	A string of characters, enclosed in double quotes
72914.	**print** **E** **,** ... **,** **E**
73015.	**I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for
731	a **void** function (see the *Void Functions* subsection of the
732	**FUNCTIONS** section). The **E** argument(s) may also be arrays of the form
733	**I[]**, which will automatically be turned into array references (see the
734	*Array References* subsection of the **FUNCTIONS** section) if the
735	corresponding parameter in the function definition is an array reference.
736
737Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**.
738
739Also, as a **non-portable extension**, any or all of the expressions in the
740header of a for loop may be omitted. If the condition (second expression) is
741omitted, it is assumed to be a constant **1**.
742
743The **break** statement causes a loop to stop iterating and resume execution
744immediately following a loop. This is only allowed in loops.
745
746The **continue** statement causes a loop iteration to stop early and returns to
747the start of the loop, including testing the loop condition. This is only
748allowed in loops.
749
750The **if** **else** statement does the same thing as in C.
751
752The **quit** statement causes bc(1) to quit, even if it is on a branch that will
753not be executed (it is a compile-time command).
754
755The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit**
756if it is on a branch of an **if** statement that is not executed, bc(1) does not
757quit.)
758
759The **limits** statement prints the limits that this bc(1) is subject to. This
760is like the **quit** statement in that it is a compile-time command.
761
762An expression by itself is evaluated and printed, followed by a newline.
763
764Both scientific notation and engineering notation are available for printing the
765results of expressions. Scientific notation is activated by assigning **0** to
766**obase**, and engineering notation is activated by assigning **1** to
767**obase**. To deactivate them, just assign a different value to **obase**.
768
769Scientific notation and engineering notation are disabled if bc(1) is run with
770either the **-s** or **-w** command-line options (or equivalents).
771
772Printing numbers in scientific notation and/or engineering notation is a
773**non-portable extension**.
774
775## Print Statement
776
777The "expressions" in a **print** statement may also be strings. If they are, there
778are backslash escape sequences that are interpreted specially. What those
779sequences are, and what they cause to be printed, are shown below:
780
781-------- -------
782**\\a**  **\\a**
783**\\b**  **\\b**
784**\\\\** **\\**
785**\\e**  **\\**
786**\\f**  **\\f**
787**\\n**  **\\n**
788**\\q**  **"**
789**\\r**  **\\r**
790**\\t**  **\\t**
791-------- -------
792
793Any other character following a backslash causes the backslash and character to
794be printed as-is.
795
796Any non-string expression in a print statement shall be assigned to **last**,
797like any other expression that is printed.
798
799## Order of Evaluation
800
801All expressions in a statment are evaluated left to right, except as necessary
802to maintain order of operations. This means, for example, assuming that **i** is
803equal to **0**, in the expression
804
805    a[i++] = i++
806
807the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2**
808at the end of the expression.
809
810This includes function arguments. Thus, assuming **i** is equal to **0**, this
811means that in the expression
812
813    x(i++, i++)
814
815the first argument passed to **x()** is **0**, and the second argument is **1**,
816while **i** is equal to **2** before the function starts executing.
817
818# FUNCTIONS
819
820Function definitions are as follows:
821
822```
823define I(I,...,I){
824	auto I,...,I
825	S;...;S
826	return(E)
827}
828```
829
830Any **I** in the parameter list or **auto** list may be replaced with **I[]** to
831make a parameter or **auto** var an array, and any **I** in the parameter list
832may be replaced with **\*I[]** to make a parameter an array reference. Callers
833of functions that take array references should not put an asterisk in the call;
834they must be called with just **I[]** like normal array parameters and will be
835automatically converted into references.
836
837As a **non-portable extension**, the opening brace of a **define** statement may
838appear on the next line.
839
840As a **non-portable extension**, the return statement may also be in one of the
841following forms:
842
8431.	**return**
8442.	**return** **(** **)**
8453.	**return** **E**
846
847The first two, or not specifying a **return** statement, is equivalent to
848**return (0)**, unless the function is a **void** function (see the *Void
849Functions* subsection below).
850
851## Void Functions
852
853Functions can also be **void** functions, defined as follows:
854
855```
856define void I(I,...,I){
857	auto I,...,I
858	S;...;S
859	return
860}
861```
862
863They can only be used as standalone expressions, where such an expression would
864be printed alone, except in a print statement.
865
866Void functions can only use the first two **return** statements listed above.
867They can also omit the return statement entirely.
868
869The word "void" is not treated as a keyword; it is still possible to have
870variables, arrays, and functions named **void**. The word "void" is only
871treated specially right after the **define** keyword.
872
873This is a **non-portable extension**.
874
875## Array References
876
877For any array in the parameter list, if the array is declared in the form
878
879```
880*I[]
881```
882
883it is a **reference**. Any changes to the array in the function are reflected,
884when the function returns, to the array that was passed in.
885
886Other than this, all function arguments are passed by value.
887
888This is a **non-portable extension**.
889
890# LIBRARY
891
892All of the functions below, including the functions in the extended math
893library (see the *Extended Library* subsection below), are available when the
894**-l** or **-\-mathlib** command-line flags are given, except that the extended
895math library is not available when the **-s** option, the **-w** option, or
896equivalents are given.
897
898## Standard Library
899
900The [standard][1] defines the following functions for the math library:
901
902**s(x)**
903
904:   Returns the sine of **x**, which is assumed to be in radians.
905
906    This is a transcendental function (see the *Transcendental Functions*
907    subsection below).
908
909**c(x)**
910
911:   Returns the cosine of **x**, which is assumed to be in radians.
912
913    This is a transcendental function (see the *Transcendental Functions*
914    subsection below).
915
916**a(x)**
917
918:   Returns the arctangent of **x**, in radians.
919
920    This is a transcendental function (see the *Transcendental Functions*
921    subsection below).
922
923**l(x)**
924
925:   Returns the natural logarithm of **x**.
926
927    This is a transcendental function (see the *Transcendental Functions*
928    subsection below).
929
930**e(x)**
931
932:   Returns the mathematical constant **e** raised to the power of **x**.
933
934    This is a transcendental function (see the *Transcendental Functions*
935    subsection below).
936
937**j(x, n)**
938
939:   Returns the bessel integer order **n** (truncated) of **x**.
940
941    This is a transcendental function (see the *Transcendental Functions*
942    subsection below).
943
944## Extended Library
945
946The extended library is *not* loaded when the **-s**/**-\-standard** or
947**-w**/**-\-warn** options are given since they are not part of the library
948defined by the [standard][1].
949
950The extended library is a **non-portable extension**.
951
952**p(x, y)**
953
954:   Calculates **x** to the power of **y**, even if **y** is not an integer, and
955    returns the result to the current **scale**.
956
957    It is an error if **y** is negative and **x** is **0**.
958
959    This is a transcendental function (see the *Transcendental Functions*
960    subsection below).
961
962**r(x, p)**
963
964:   Returns **x** rounded to **p** decimal places according to the rounding mode
965    [round half away from **0**][3].
966
967**ceil(x, p)**
968
969:   Returns **x** rounded to **p** decimal places according to the rounding mode
970    [round away from **0**][6].
971
972**f(x)**
973
974:   Returns the factorial of the truncated absolute value of **x**.
975
976**perm(n, k)**
977
978:   Returns the permutation of the truncated absolute value of **n** of the
979    truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
980
981**comb(n, k)**
982
983:   Returns the combination of the truncated absolute value of **n** of the
984    truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**.
985
986**l2(x)**
987
988:   Returns the logarithm base **2** of **x**.
989
990    This is a transcendental function (see the *Transcendental Functions*
991    subsection below).
992
993**l10(x)**
994
995:   Returns the logarithm base **10** of **x**.
996
997    This is a transcendental function (see the *Transcendental Functions*
998    subsection below).
999
1000**log(x, b)**
1001
1002:   Returns the logarithm base **b** of **x**.
1003
1004    This is a transcendental function (see the *Transcendental Functions*
1005    subsection below).
1006
1007**cbrt(x)**
1008
1009:   Returns the cube root of **x**.
1010
1011**root(x, n)**
1012
1013:   Calculates the truncated value of **n**, **r**, and returns the **r**th root
1014    of **x** to the current **scale**.
1015
1016    If **r** is **0** or negative, this raises an error and causes bc(1) to
1017    reset (see the **RESET** section). It also raises an error and causes bc(1)
1018    to reset if **r** is even and **x** is negative.
1019
1020**pi(p)**
1021
1022:   Returns **pi** to **p** decimal places.
1023
1024    This is a transcendental function (see the *Transcendental Functions*
1025    subsection below).
1026
1027**t(x)**
1028
1029:   Returns the tangent of **x**, which is assumed to be in radians.
1030
1031    This is a transcendental function (see the *Transcendental Functions*
1032    subsection below).
1033
1034**a2(y, x)**
1035
1036:   Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
1037    equal to **0**, it raises an error and causes bc(1) to reset (see the
1038    **RESET** section). Otherwise, if **x** is greater than **0**, it returns
1039    **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
1040    to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
1041    is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
1042    and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
1043    **0**, and **y** is less than **0**, it returns **-pi/2**.
1044
1045    This function is the same as the **atan2()** function in many programming
1046    languages.
1047
1048    This is a transcendental function (see the *Transcendental Functions*
1049    subsection below).
1050
1051**sin(x)**
1052
1053:   Returns the sine of **x**, which is assumed to be in radians.
1054
1055    This is an alias of **s(x)**.
1056
1057    This is a transcendental function (see the *Transcendental Functions*
1058    subsection below).
1059
1060**cos(x)**
1061
1062:   Returns the cosine of **x**, which is assumed to be in radians.
1063
1064    This is an alias of **c(x)**.
1065
1066    This is a transcendental function (see the *Transcendental Functions*
1067    subsection below).
1068
1069**tan(x)**
1070
1071:   Returns the tangent of **x**, which is assumed to be in radians.
1072
1073    If **x** is equal to **1** or **-1**, this raises an error and causes bc(1)
1074    to reset (see the **RESET** section).
1075
1076    This is an alias of **t(x)**.
1077
1078    This is a transcendental function (see the *Transcendental Functions*
1079    subsection below).
1080
1081**atan(x)**
1082
1083:   Returns the arctangent of **x**, in radians.
1084
1085    This is an alias of **a(x)**.
1086
1087    This is a transcendental function (see the *Transcendental Functions*
1088    subsection below).
1089
1090**atan2(y, x)**
1091
1092:   Returns the arctangent of **y/x**, in radians. If both **y** and **x** are
1093    equal to **0**, it raises an error and causes bc(1) to reset (see the
1094    **RESET** section). Otherwise, if **x** is greater than **0**, it returns
1095    **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal
1096    to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y**
1097    is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**,
1098    and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to
1099    **0**, and **y** is less than **0**, it returns **-pi/2**.
1100
1101    This function is the same as the **atan2()** function in many programming
1102    languages.
1103
1104    This is an alias of **a2(y, x)**.
1105
1106    This is a transcendental function (see the *Transcendental Functions*
1107    subsection below).
1108
1109**r2d(x)**
1110
1111:   Converts **x** from radians to degrees and returns the result.
1112
1113    This is a transcendental function (see the *Transcendental Functions*
1114    subsection below).
1115
1116**d2r(x)**
1117
1118:   Converts **x** from degrees to radians and returns the result.
1119
1120    This is a transcendental function (see the *Transcendental Functions*
1121    subsection below).
1122
1123**frand(p)**
1124
1125:   Generates a pseudo-random number between **0** (inclusive) and **1**
1126    (exclusive) with the number of decimal digits after the decimal point equal
1127    to the truncated absolute value of **p**. If **p** is not **0**, then
1128    calling this function will change the value of **seed**. If **p** is **0**,
1129    then **0** is returned, and **seed** is *not* changed.
1130
1131**ifrand(i, p)**
1132
1133:   Generates a pseudo-random number that is between **0** (inclusive) and the
1134    truncated absolute value of **i** (exclusive) with the number of decimal
1135    digits after the decimal point equal to the truncated absolute value of
1136    **p**. If the absolute value of **i** is greater than or equal to **2**, and
1137    **p** is not **0**, then calling this function will change the value of
1138    **seed**; otherwise, **0** is returned and **seed** is not changed.
1139
1140**srand(x)**
1141
1142:   Returns **x** with its sign flipped with probability **0.5**. In other
1143    words, it randomizes the sign of **x**.
1144
1145**brand()**
1146
1147:   Returns a random boolean value (either **0** or **1**).
1148
1149**ubytes(x)**
1150
1151:   Returns the numbers of unsigned integer bytes required to hold the truncated
1152    absolute value of **x**.
1153
1154**sbytes(x)**
1155
1156:   Returns the numbers of signed, two's-complement integer bytes required to
1157    hold the truncated value of **x**.
1158
1159**hex(x)**
1160
1161:   Outputs the hexadecimal (base **16**) representation of **x**.
1162
1163    This is a **void** function (see the *Void Functions* subsection of the
1164    **FUNCTIONS** section).
1165
1166**binary(x)**
1167
1168:   Outputs the binary (base **2**) representation of **x**.
1169
1170    This is a **void** function (see the *Void Functions* subsection of the
1171    **FUNCTIONS** section).
1172
1173**output(x, b)**
1174
1175:   Outputs the base **b** representation of **x**.
1176
1177    This is a **void** function (see the *Void Functions* subsection of the
1178    **FUNCTIONS** section).
1179
1180**uint(x)**
1181
1182:   Outputs the representation, in binary and hexadecimal, of **x** as an
1183    unsigned integer in as few power of two bytes as possible. Both outputs are
1184    split into bytes separated by spaces.
1185
1186    If **x** is not an integer or is negative, an error message is printed
1187    instead, but bc(1) is not reset (see the **RESET** section).
1188
1189    This is a **void** function (see the *Void Functions* subsection of the
1190    **FUNCTIONS** section).
1191
1192**int(x)**
1193
1194:   Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1195    two's-complement integer in as few power of two bytes as possible. Both
1196    outputs are split into bytes separated by spaces.
1197
1198    If **x** is not an integer, an error message is printed instead, but bc(1)
1199    is not reset (see the **RESET** section).
1200
1201    This is a **void** function (see the *Void Functions* subsection of the
1202    **FUNCTIONS** section).
1203
1204**uintn(x, n)**
1205
1206:   Outputs the representation, in binary and hexadecimal, of **x** as an
1207    unsigned integer in **n** bytes. Both outputs are split into bytes separated
1208    by spaces.
1209
1210    If **x** is not an integer, is negative, or cannot fit into **n** bytes, an
1211    error message is printed instead, but bc(1) is not reset (see the **RESET**
1212    section).
1213
1214    This is a **void** function (see the *Void Functions* subsection of the
1215    **FUNCTIONS** section).
1216
1217**intn(x, n)**
1218
1219:   Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1220    two's-complement integer in **n** bytes. Both outputs are split into bytes
1221    separated by spaces.
1222
1223    If **x** is not an integer or cannot fit into **n** bytes, an error message
1224    is printed instead, but bc(1) is not reset (see the **RESET** section).
1225
1226    This is a **void** function (see the *Void Functions* subsection of the
1227    **FUNCTIONS** section).
1228
1229**uint8(x)**
1230
1231:   Outputs the representation, in binary and hexadecimal, of **x** as an
1232    unsigned integer in **1** byte. Both outputs are split into bytes separated
1233    by spaces.
1234
1235    If **x** is not an integer, is negative, or cannot fit into **1** byte, an
1236    error message is printed instead, but bc(1) is not reset (see the **RESET**
1237    section).
1238
1239    This is a **void** function (see the *Void Functions* subsection of the
1240    **FUNCTIONS** section).
1241
1242**int8(x)**
1243
1244:   Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1245    two's-complement integer in **1** byte. Both outputs are split into bytes
1246    separated by spaces.
1247
1248    If **x** is not an integer or cannot fit into **1** byte, an error message
1249    is printed instead, but bc(1) is not reset (see the **RESET** section).
1250
1251    This is a **void** function (see the *Void Functions* subsection of the
1252    **FUNCTIONS** section).
1253
1254**uint16(x)**
1255
1256:   Outputs the representation, in binary and hexadecimal, of **x** as an
1257    unsigned integer in **2** bytes. Both outputs are split into bytes separated
1258    by spaces.
1259
1260    If **x** is not an integer, is negative, or cannot fit into **2** bytes, an
1261    error message is printed instead, but bc(1) is not reset (see the **RESET**
1262    section).
1263
1264    This is a **void** function (see the *Void Functions* subsection of the
1265    **FUNCTIONS** section).
1266
1267**int16(x)**
1268
1269:   Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1270    two's-complement integer in **2** bytes. Both outputs are split into bytes
1271    separated by spaces.
1272
1273    If **x** is not an integer or cannot fit into **2** bytes, an error message
1274    is printed instead, but bc(1) is not reset (see the **RESET** section).
1275
1276    This is a **void** function (see the *Void Functions* subsection of the
1277    **FUNCTIONS** section).
1278
1279**uint32(x)**
1280
1281:   Outputs the representation, in binary and hexadecimal, of **x** as an
1282    unsigned integer in **4** bytes. Both outputs are split into bytes separated
1283    by spaces.
1284
1285    If **x** is not an integer, is negative, or cannot fit into **4** bytes, an
1286    error message is printed instead, but bc(1) is not reset (see the **RESET**
1287    section).
1288
1289    This is a **void** function (see the *Void Functions* subsection of the
1290    **FUNCTIONS** section).
1291
1292**int32(x)**
1293
1294:   Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1295    two's-complement integer in **4** bytes. Both outputs are split into bytes
1296    separated by spaces.
1297
1298    If **x** is not an integer or cannot fit into **4** bytes, an error message
1299    is printed instead, but bc(1) is not reset (see the **RESET** section).
1300
1301    This is a **void** function (see the *Void Functions* subsection of the
1302    **FUNCTIONS** section).
1303
1304**uint64(x)**
1305
1306:   Outputs the representation, in binary and hexadecimal, of **x** as an
1307    unsigned integer in **8** bytes. Both outputs are split into bytes separated
1308    by spaces.
1309
1310    If **x** is not an integer, is negative, or cannot fit into **8** bytes, an
1311    error message is printed instead, but bc(1) is not reset (see the **RESET**
1312    section).
1313
1314    This is a **void** function (see the *Void Functions* subsection of the
1315    **FUNCTIONS** section).
1316
1317**int64(x)**
1318
1319:   Outputs the representation, in binary and hexadecimal, of **x** as a signed,
1320    two's-complement integer in **8** bytes. Both outputs are split into bytes
1321    separated by spaces.
1322
1323    If **x** is not an integer or cannot fit into **8** bytes, an error message
1324    is printed instead, but bc(1) is not reset (see the **RESET** section).
1325
1326    This is a **void** function (see the *Void Functions* subsection of the
1327    **FUNCTIONS** section).
1328
1329**hex_uint(x, n)**
1330
1331:   Outputs the representation of the truncated absolute value of **x** as an
1332    unsigned integer in hexadecimal using **n** bytes. Not all of the value will
1333    be output if **n** is too small.
1334
1335    This is a **void** function (see the *Void Functions* subsection of the
1336    **FUNCTIONS** section).
1337
1338**binary_uint(x, n)**
1339
1340:   Outputs the representation of the truncated absolute value of **x** as an
1341    unsigned integer in binary using **n** bytes. Not all of the value will be
1342    output if **n** is too small.
1343
1344    This is a **void** function (see the *Void Functions* subsection of the
1345    **FUNCTIONS** section).
1346
1347**output_uint(x, n)**
1348
1349:   Outputs the representation of the truncated absolute value of **x** as an
1350    unsigned integer in the current **obase** (see the **SYNTAX** section) using
1351    **n** bytes. Not all of the value will be output if **n** is too small.
1352
1353    This is a **void** function (see the *Void Functions* subsection of the
1354    **FUNCTIONS** section).
1355
1356**output_byte(x, i)**
1357
1358:   Outputs byte **i** of the truncated absolute value of **x**, where **0** is
1359    the least significant byte and **number_of_bytes - 1** is the most
1360    significant byte.
1361
1362    This is a **void** function (see the *Void Functions* subsection of the
1363    **FUNCTIONS** section).
1364
1365## Transcendental Functions
1366
1367All transcendental functions can return slightly inaccurate results (up to 1
1368[ULP][4]). This is unavoidable, and [this article][5] explains why it is
1369impossible and unnecessary to calculate exact results for the transcendental
1370functions.
1371
1372Because of the possible inaccuracy, I recommend that users call those functions
1373with the precision (**scale**) set to at least 1 higher than is necessary. If
1374exact results are *absolutely* required, users can double the precision
1375(**scale**) and then truncate.
1376
1377The transcendental functions in the standard math library are:
1378
1379* **s(x)**
1380* **c(x)**
1381* **a(x)**
1382* **l(x)**
1383* **e(x)**
1384* **j(x, n)**
1385
1386The transcendental functions in the extended math library are:
1387
1388* **l2(x)**
1389* **l10(x)**
1390* **log(x, b)**
1391* **pi(p)**
1392* **t(x)**
1393* **a2(y, x)**
1394* **sin(x)**
1395* **cos(x)**
1396* **tan(x)**
1397* **atan(x)**
1398* **atan2(y, x)**
1399* **r2d(x)**
1400* **d2r(x)**
1401
1402# RESET
1403
1404When bc(1) encounters an error or a signal that it has a non-default handler
1405for, it resets. This means that several things happen.
1406
1407First, any functions that are executing are stopped and popped off the stack.
1408The behavior is not unlike that of exceptions in programming languages. Then
1409the execution point is set so that any code waiting to execute (after all
1410functions returned) is skipped.
1411
1412Thus, when bc(1) resets, it skips any remaining code waiting to be executed.
1413Then, if it is interactive mode, and the error was not a fatal error (see the
1414**EXIT STATUS** section), it asks for more input; otherwise, it exits with the
1415appropriate return code.
1416
1417Note that this reset behavior is different from the GNU bc(1), which attempts to
1418start executing the statement right after the one that caused an error.
1419
1420# PERFORMANCE
1421
1422Most bc(1) implementations use **char** types to calculate the value of **1**
1423decimal digit at a time, but that can be slow. This bc(1) does something
1424different.
1425
1426It uses large integers to calculate more than **1** decimal digit at a time. If
1427built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is
1428**64**, then each integer has **9** decimal digits. If built in an environment
1429where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1430value (the number of decimal digits per large integer) is called
1431**BC_BASE_DIGS**.
1432
1433The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with
1434the **limits** statement.
1435
1436In addition, this bc(1) uses an even larger integer for overflow checking. This
1437integer type depends on the value of **BC_LONG_BIT**, but is always at least
1438twice as large as the integer type used to store digits.
1439
1440# LIMITS
1441
1442The following are the limits on bc(1):
1443
1444**BC_LONG_BIT**
1445
1446:   The number of bits in the **long** type in the environment where bc(1) was
1447    built. This determines how many decimal digits can be stored in a single
1448    large integer (see the **PERFORMANCE** section).
1449
1450**BC_BASE_DIGS**
1451
1452:   The number of decimal digits per large integer (see the **PERFORMANCE**
1453    section). Depends on **BC_LONG_BIT**.
1454
1455**BC_BASE_POW**
1456
1457:   The max decimal number that each large integer can store (see
1458    **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**.
1459
1460**BC_OVERFLOW_MAX**
1461
1462:   The max number that the overflow type (see the **PERFORMANCE** section) can
1463    hold. Depends on **BC_LONG_BIT**.
1464
1465**BC_BASE_MAX**
1466
1467:   The maximum output base. Set at **BC_BASE_POW**.
1468
1469**BC_DIM_MAX**
1470
1471:   The maximum size of arrays. Set at **SIZE_MAX-1**.
1472
1473**BC_SCALE_MAX**
1474
1475:   The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**.
1476
1477**BC_STRING_MAX**
1478
1479:   The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**.
1480
1481**BC_NAME_MAX**
1482
1483:   The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**.
1484
1485**BC_NUM_MAX**
1486
1487:   The maximum length of a number (in decimal digits), which includes digits
1488    after the decimal point. Set at **BC_OVERFLOW_MAX-1**.
1489
1490**BC_RAND_MAX**
1491
1492:   The maximum integer (inclusive) returned by the **rand()** operand. Set at
1493    **2\^BC_LONG_BIT-1**.
1494
1495Exponent
1496
1497:   The maximum allowable exponent (positive or negative). Set at
1498    **BC_OVERFLOW_MAX**.
1499
1500Number of vars
1501
1502:   The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
1503
1504The actual values can be queried with the **limits** statement.
1505
1506These limits are meant to be effectively non-existent; the limits are so large
1507(at least on 64-bit machines) that there should not be any point at which they
1508become a problem. In fact, memory should be exhausted before these limits should
1509be hit.
1510
1511# ENVIRONMENT VARIABLES
1512
1513bc(1) recognizes the following environment variables:
1514
1515**POSIXLY_CORRECT**
1516
1517:   If this variable exists (no matter the contents), bc(1) behaves as if
1518    the **-s** option was given.
1519
1520**BC_ENV_ARGS**
1521
1522:   This is another way to give command-line arguments to bc(1). They should be
1523    in the same format as all other command-line arguments. These are always
1524    processed first, so any files given in **BC_ENV_ARGS** will be processed
1525    before arguments and files given on the command-line. This gives the user
1526    the ability to set up "standard" options and files to be used at every
1527    invocation. The most useful thing for such files to contain would be useful
1528    functions that the user might want every time bc(1) runs.
1529
1530    The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments,
1531    but it does not understand escape sequences. For example, the string
1532    **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string
1533    **"/home/gavin/some \"bc\" file.bc"** will include the backslashes.
1534
1535    The quote parsing will handle either kind of quotes, **'** or **"**. Thus,
1536    if you have a file with any number of single quotes in the name, you can use
1537    double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice
1538    versa if you have a file with double quotes. However, handling a file with
1539    both kinds of quotes in **BC_ENV_ARGS** is not supported due to the
1540    complexity of the parsing, though such files are still supported on the
1541    command-line where the parsing is done by the shell.
1542
1543**BC_LINE_LENGTH**
1544
1545:   If this environment variable exists and contains an integer that is greater
1546    than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output
1547    lines to that length, including the backslash (**\\**). The default line
1548    length is **70**.
1549
1550# EXIT STATUS
1551
1552bc(1) returns the following exit statuses:
1553
1554**0**
1555
1556:   No error.
1557
1558**1**
1559
1560:   A math error occurred. This follows standard practice of using **1** for
1561    expected errors, since math errors will happen in the process of normal
1562    execution.
1563
1564    Math errors include divide by **0**, taking the square root of a negative
1565    number, using a negative number as a bound for the pseudo-random number
1566    generator, attempting to convert a negative number to a hardware integer,
1567    overflow when converting a number to a hardware integer, and attempting to
1568    use a non-integer where an integer is required.
1569
1570    Converting to a hardware integer happens for the second operand of the power
1571    (**\^**), places (**\@**), left shift (**\<\<**), and right shift (**\>\>**)
1572    operators and their corresponding assignment operators.
1573
1574**2**
1575
1576:   A parse error occurred.
1577
1578    Parse errors include unexpected **EOF**, using an invalid character, failing
1579    to find the end of a string or comment, using a token where it is invalid,
1580    giving an invalid expression, giving an invalid print statement, giving an
1581    invalid function definition, attempting to assign to an expression that is
1582    not a named expression (see the *Named Expressions* subsection of the
1583    **SYNTAX** section), giving an invalid **auto** list, having a duplicate
1584    **auto**/function parameter, failing to find the end of a code block,
1585    attempting to return a value from a **void** function, attempting to use a
1586    variable as a reference, and using any extensions when the option **-s** or
1587    any equivalents were given.
1588
1589**3**
1590
1591:   A runtime error occurred.
1592
1593    Runtime errors include assigning an invalid number to **ibase**, **obase**,
1594    or **scale**; give a bad expression to a **read()** call, calling **read()**
1595    inside of a **read()** call, type errors, passing the wrong number of
1596    arguments to functions, attempting to call an undefined function, and
1597    attempting to use a **void** function call as a value in an expression.
1598
1599**4**
1600
1601:   A fatal error occurred.
1602
1603    Fatal errors include memory allocation errors, I/O errors, failing to open
1604    files, attempting to use files that do not have only ASCII characters (bc(1)
1605    only accepts ASCII characters), attempting to open a directory as a file,
1606    and giving invalid command-line options.
1607
1608The exit status **4** is special; when a fatal error occurs, bc(1) always exits
1609and returns **4**, no matter what mode bc(1) is in.
1610
1611The other statuses will only be returned when bc(1) is not in interactive mode
1612(see the **INTERACTIVE MODE** section), since bc(1) resets its state (see the
1613**RESET** section) and accepts more input when one of those errors occurs in
1614interactive mode. This is also the case when interactive mode is forced by the
1615**-i** flag or **-\-interactive** option.
1616
1617These exit statuses allow bc(1) to be used in shell scripting with error
1618checking, and its normal behavior can be forced by using the **-i** flag or
1619**-\-interactive** option.
1620
1621# INTERACTIVE MODE
1622
1623Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode.
1624Interactive mode is turned on automatically when both **stdin** and **stdout**
1625are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
1626turn it on in other cases.
1627
1628In interactive mode, bc(1) attempts to recover from errors (see the **RESET**
1629section), and in normal execution, flushes **stdout** as soon as execution is
1630done for the current input.
1631
1632# TTY MODE
1633
1634If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns
1635on "TTY mode."
1636
1637The prompt is enabled in TTY mode.
1638
1639TTY mode is different from interactive mode because interactive mode is required
1640in the [bc(1) specification][1], and interactive mode requires only **stdin**
1641and **stdout** to be connected to a terminal.
1642
1643# SIGNAL HANDLING
1644
1645Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If
1646bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the
1647**RESET** section). Otherwise, it will clean up and exit.
1648
1649Note that "current input" can mean one of two things. If bc(1) is processing
1650input from **stdin** in TTY mode, it will ask for more input. If bc(1) is
1651processing input from a file in TTY mode, it will stop processing the file and
1652start processing the next file, if one exists, or ask for input from **stdin**
1653if no other file exists.
1654
1655This means that if a **SIGINT** is sent to bc(1) as it is executing a file, it
1656can seem as though bc(1) did not respond to the signal since it will immediately
1657start executing the next file. This is by design; most files that users execute
1658when interacting with bc(1) have function definitions, which are quick to parse.
1659If a file takes a long time to execute, there may be a bug in that file. The
1660rest of the files could still be executed without problem, allowing the user to
1661continue.
1662
1663**SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the
1664default handler for all other signals.
1665
1666# LOCALES
1667
1668This bc(1) ships with support for adding error messages for different locales
1669and thus, supports **LC_MESSAGES**.
1670
1671# SEE ALSO
1672
1673dc(1)
1674
1675# STANDARDS
1676
1677bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1]
1678specification. The flags **-efghiqsvVw**, all long options, and the extensions
1679noted above are extensions to that specification.
1680
1681Note that the specification explicitly says that bc(1) only accepts numbers that
1682use a period (**.**) as a radix point, regardless of the value of
1683**LC_NUMERIC**.
1684
1685This bc(1) supports error messages for different locales, and thus, it supports
1686**LC_MESSAGES**.
1687
1688# BUGS
1689
1690None are known. Report bugs at https://git.yzena.com/gavin/bc.
1691
1692# AUTHORS
1693
1694Gavin D. Howard <gavin@yzena.com> and contributors.
1695
1696[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
1697[2]: https://www.gnu.org/software/bc/
1698[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero
1699[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place
1700[5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT
1701[6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero
1702