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