1bc(1) -- arbitrary-precision arithmetic language and calculator 2=============================================================== 3 4SYNOPSIS 5-------- 6 7`bc` [`-ghilPqsvVw`] [`--global-stacks`] [`--help`] [`--interactive`] 8[`--mathlib`] [`--no-prompt`] [`--quiet`] [`--standard`] [`--warn`] 9[`--version`] [`-e` *expr*] [`--expression=`*expr*...] [`-f` *file*...] 10[`-file=`*file*...] [*file*...] 11 12DESCRIPTION 13----------- 14 15bc(1) is an interactive processor for a language first standardized in 1991 by 16POSIX. (The current standard is [here][1].) The language provides unlimited 17precision decimal arithmetic and is somewhat C-like, but there are differences. 18Such differences will be noted in this document. 19 20After parsing and handling options, this bc(1) reads any files given on the 21command line and executes them before reading from `stdin`. 22 23With all build options, except for extra math, enabled this bc(1) is a drop-in 24replacement for ***any*** bc(1), including (and especially) the GNU bc(1). It is 25also a drop-in replacement for any bc(1) if extra math is enabled, but it will 26have extra features not found in other bc(1) implementations. 27 28OPTIONS 29------- 30 31The following are the options that bc(1) accepts. 32 33 * `-g`, `--global-stacks`: 34 Turns the globals `ibase`, `obase`, and `scale` into stacks. 35 36 This has the effect that a copy of the current value of all three are pushed 37 onto a stack for every function call, as well as popped when every function 38 returns. This means that functions can assign to any and all of those 39 globals without worrying that the change will affect other functions. 40 Thus, `output(x,b)` (in the [extended library](#extended-library)) could 41 have been written like this: 42 43 `define void output(x, b) { obase=b; x }` 44 45 instead of like this: 46 47 `define void output(x, b) { auto c; c=obase; obase=b; x; obase=c }` 48 49 This makes writing functions much easier. 50 51 However, since using this flag means that functions cannot set `ibase`, 52 `obase`, or `scale` globally, functions that are made to do so cannot work 53 anymore. There are two possible use cases for that, and each has a solution. 54 55 First, if a function is called on startup to turn bc(1) into a number 56 converter, it is possible to replace that capability with various shell 57 aliases. Examples: 58 59 `alias d2o="bc -e ibase=A -e obase=8"; alias h2b="bc -e ibase=G -e obase=2"` 60 61 Second, if the purpose of a function is to set `ibase`, `obase`, or `scale` 62 globally for any other purpose, it could be split into one to three 63 functions (based on how many globals it sets) and each of those functions 64 could return the desired value for a global. 65 66 If this behavior is desired for every run of bc(1), then users could make 67 sure to define `BC_ENV_ARGS` and include this option (see the 68 ENVIRONMENT VARIABLES section for more details). 69 70 If `-s`, `-w`, or any equivalents are used, this option is ignored. 71 72 This is a **non-portable extension**. 73 74 * `-h`, `--help`: 75 Prints a usage message and quits. 76 77 * `-i`, `--interactive`: 78 Forces interactive mode. 79 80 Per the [standard][1], bc(1) has an interactive mode and a non-interactive 81 mode. The interactive mode is turned on automatically when both `stdin` and 82 `stdout` are hooked to a terminal, but this flag can turn it on in other 83 cases. In interactive mode, bc(1) attempts to recover from errors (see the 84 RESET section), and in normal execution, flushes `stdout` as soon as 85 execution is done for the current input. 86 87 This is a **non-portable extension**. 88 89 * `-l`, `--mathlib`: 90 Sets `scale` (see the Scale section) to `20` and loads the included math 91 library before running any code, including any expressions or files 92 specified on the command line. 93 94 To learn what is in the library, see the LIBRARY section. 95 96 * `-P`, `--no-prompt`: 97 Disables the prompt in interactive mode. This is mostly for those users that 98 do not want a prompt or are not used to having them in `bc`. Most of those 99 users would want to put this option in `BC_ENV_ARGS`. 100 101 If the prompt has been disabled while building bc(1), this option is a 102 no-op. 103 104 This is a **non-portable extension**. 105 106 * `-q`, `--quiet`: 107 Do not print copyright header. bc(1) will also suppress the header in 108 non-interactive mode. 109 110 This is mostly for compatibility with the [GNU bc(1)][2]. 111 112 This is a **non-portable extension**. 113 114 * `-s`, `--standard`: 115 Process exactly the language defined by the [standard][1] and error if any 116 extensions are used. 117 118 This is a **non-portable extension**. 119 120 * `-v`, `-V`, `--version`: 121 Print the version information (copyright header) and exit. 122 123 This is a **non-portable extension**. 124 125 * `-w`, `--warn`: 126 Like `-s` and `--standard`, except that warnings (and not errors) are given 127 for non-standard extensions. 128 129 This is a **non-portable extension**. 130 131 * `-e` *expr*, `--expression`=*expr*: 132 Evaluates `expr`. If multiple expressions are given, they are evaluated in 133 order. If files are given as well (see below), the expressions and files are 134 evaluated in the order given. This means that if a file is given before an 135 expression, the file is read in and evaluated first. 136 137 In other bc(1) implementations, this option causes the program to execute 138 the expressions and then exit. This bc(1) does not, unless the 139 `BC_EXPR_EXIT` is defined (see the ENVIRONMENT VARIABLES section). 140 141 This is a **non-portable extension**. 142 143 * `-f` *file*, `--file`=*file*: 144 Reads in `file` and evaluates it. If expressions are also given (see above), 145 the expressions are evaluated in the order given. 146 147 In other bc(1) implementations, this option causes the program to execute 148 the files and then exit. This bc(1) does not, unless the 149 `BC_EXPR_EXIT` is defined (see the ENVIRONMENT VARIABLES section). 150 151 This is a **non-portable extension**. 152 153STDOUT 154------ 155 156Any non-error output is written to `stdout`. 157 158**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal 159error (see the EXIT STATUS section) if it cannot write to `stdout`, so if 160`stdout` is closed, as in `bc <file> >&-`, it will quit with an error. This is 161done so that bc(1) can report problems when `stdout` is redirected to a file. 162 163If there are scripts that depend on the behavior of other bc(1) implementations, 164it is recommended that those scripts be changed to redirect `stdout` to 165`/dev/null`. 166 167STDERR 168------ 169 170Any error output is written to `stderr`. 171 172**Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal 173error (see the EXIT STATUS section) if it cannot write to `stderr`, so if 174`stderr` is closed, as in `bc <file> 2>&-`, it will quit with an error. This is 175done so that bc(1) can report problems when `stderr` is redirected to a file. 176 177If there are scripts that depend on the behavior of other bc(1) implementations, 178it is recommended that those scripts be changed to redirect `stderr` to 179`/dev/null`. 180 181SYNTAX 182------ 183 184The syntax for bc(1) programs is mostly C-like, with some differences. This 185bc(1) follows the [POSIX standard][1], which is a much more thorough resource 186for the language this bc(1) accepts. This section is meant to be a summary and a 187listing of all the extensions to the [standard][1]. 188 189In the sections below, `E` means expression, `S` means statement, and `I` means 190identifier. 191 192Identifiers (`I`) start with a lowercase letter and can be followed by any 193number (up to `BC_NAME_MAX-1`) of lowercase letters (`a-z`), digits (`0-9`), and 194underscores (`_`). The regex is `[a-z][a-z0-9_]*` Identifiers with more than one 195character (letter) are a **non-portable extension**. 196 197`ibase` is a global variable determining how to interpret constant numbers. It 198is the "input" base, or the number base used for interpreting input numbers. 199`ibase` is initially `10`. If the `-s` (`--standard`) and `-w` (`--warn`) flags 200were not given on the command line, the max allowable value for `ibase` is `36`. 201Otherwise, it is `16`. The min allowable value for `ibase` is `2`. The max 202allowable value for `ibase` can be queried in bc(1) programs with the 203`maxibase()` built in function. 204 205`obase` is a global variable determining how to output results. It is the 206"output" base, or the number base used for outputting numbers. `obase` is 207initially `10`. The max allowable value for `obase` is `BC_BASE_MAX`. The min 208allowable value for `obase` is `2`, unless bc(1) was built with the extra math 209option. If it was, then the min allowable value is `0`. In this case, if `obase` 210is `0`, values are output in scientific notation, and if `obase` is `1`, values 211are output in engineering notation. (Outputting in scientific or engineering 212notation are **non-portable extensions**.) The max allowable value for `obase` 213can be queried in bc(1) programs with the `maxobase()` built in function. 214 215The **scale** of an expression is the number of digits in the result of the 216expression right of the decimal point, and `scale` is a global variable that 217sets the precision of any operations, with exceptions. `scale` is initially `0`. 218`scale` cannot be negative. The max allowable value for `scale` can be queried 219in bc(1) programs with the `maxscale()` built in function. 220 221bc(1) has both **global** variables and **local** variables. All **local** 222variables are local to the function; they are parameters or are introduced in 223the `auto` list of a function (see FUNCTIONS). If a variable is accessed which 224is not a parameter or in the `auto` list, it is assumed to be **global**. If a 225parent function has a **local** variable version of a **global** variable that 226is accessed by a function that it calls, the value of that **global** variable 227in the child function is the value of the variable in the parent function, not 228the value of the actual **global** variable. 229 230All of the above applies to arrays as well. 231 232The value of a statement that is an expression (i.e., any of the 233[Named Expressions](#bc-named-expressions) or [Operands](#bc-operands)) is 234printed unless the lowest precedence operator is an 235[`assignment`](#bc-assignment) operator ***and*** the expression is not 236surrounded by parentheses. 237 238The value that is printed is also assigned to the special variable `last`. A 239single dot (`.`) may also be used as a synonym for `last`. These are 240**non-portable extensions**. 241 242Either semicolons or newlines may separate statements. 243 244### Comments 245 246There are two kinds of comments: 247 2481. Block comments are enclosed in `/*` and `*/`. 2492. Line comments go from `#` until, and not including, the next newline. This 250 is a **non-portable extension**. 251 252<a name="bc-named-expressions"/> 253 254### Named Expressions 255 256The following are named expressions in bc(1): 257 2581. Variables: `I` 2592. Array Elements: `I[E]` 2603. `ibase` 2614. `obase` 2625. `scale` 2636. `last` or a single dot (`.`) 264 265Number 6 is a **non-portable extension**. 266 267Variables and arrays do not interfere; users can have arrays named the same as 268variables. This also applies to functions (see the FUNCTIONS section), so a user 269can have a variable, array, and function that all have the same name, and they 270will not shadow each other. 271 272Named expressions are required as the operand of 273[`increment`/`decrement` operators](#bc-increment-decrement) and as the left 274side of [`assignment` operators](#bc-assignment). 275 276<a name="bc-operands"/> 277 278### Operands 279 280The following are valid operands in bc(1): 281 2821. Numbers (see [Numbers](#bc-numbers) below). 2832. Array indices (`I[E]`). 2843. `(E)`: The value of `E` (used to change precedence). 2854. `sqrt(E)`: The square root of `E`. `E` must be non-negative. 2865. `length(E)`: The number of significant decimal digits in `E`. 2876. `length(I[])`: The number of elements in the array `I`. This is a 288 **non-portable extension**. 2897. `scale(E)`: The **scale** of `E`. 2908. `abs(E)`: The absolute value of `E`. This is a **non-portable extension**. 2919. `I()`, `I(E)`, `I(E, E)`, and so on, where `I` is an identifier for a 292 non-[void function](#void-functions). The `E` parameters may also be arrays 293 and [array references](#array-references). 29410. `read()`: Reads a line from `stdin` and uses that as an expression. The 295 result of that expression is the result of the `read()` operand. This is a 296 **non-portable extension**. 29711. `maxibase()`: The max allowable `ibase`. This is a **non-portable 298 extension**. 29912. `maxobase()`: The max allowable `obase`. This is a **non-portable 300 extension**. 30113. `maxscale()`: The max allowable `scale`. This is a **non-portable 302 extension**. 303 304<a name="bc-numbers"/> 305 306### Numbers 307 308Numbers are strings made up of digits, uppercase letters, and at most `1` period 309for a radix. Numbers can have up to `BC_NUM_MAX` digits. Uppercase letters 310equal `9` + their position in the alphabet (i.e., `A` equals `10`, or `9 + 1`). 311If a digit or letter makes no sense with the current value of `ibase`, they are 312set to the value of the highest valid digit in `ibase`. 313 314Single-character numbers (i.e., `A`) take the value that they would have if they 315were valid digits, regardless of the value of `ibase`. This means that `A` 316always equals decimal `10` and `Z` always equals decimal `35`. 317 318In addition, if bc(1) was built with the extra math option, it accepts numbers 319in scientific notation. For bc(1), an example is `1.89237e9`, which is equal to 320`1892370000`. Negative exponents are also allowed, so `4.2890e-3` is equal to 321`0.0042890`. 322 323Using scientific notation is an error or warning if the `-s` or `-w`, 324respectively, command-line options (or equivalents) are given. 325 326**WARNING**: Both the number and the exponent in scientific notation are 327interpreted according to the current `ibase`, but the number is still multiplied 328by `10^exponent` regardless of the current `ibase`. For example, if `ibase` is 329`16` and bc(1) is given the number string `"FFeA"`, the resulting decimal number 330will be `2550000000000`, and if bc(1) is given the number string `"10e-4"`, the 331resulting decimal number will be `0.0016`. 332 333Accepting input as scientific notation is a **non-portable extension**. 334 335### Operators 336 337The following arithmetic and logical operators can be used. They are listed in 338order of decreasing precedence. Operators in the same group have the same 339precedence. 340 341 * `++` `--`: 342 Type: Prefix and Postfix 343 344 Associativity: None 345 346 Description: `increment`, `decrement` 347 348 * `-` `!`: 349 Type: Prefix 350 351 Associativity: None 352 353 Description: `negation`, `boolean not` 354 355 * `$`: 356 Type: Postfix 357 358 Associativity: None 359 360 Description: `truncation` 361 362 * `@`: 363 Type: Binary 364 365 Associativity: Right 366 367 Description: `set precision` 368 369 * `^`: 370 Type: Binary 371 372 Associativity: Right 373 374 Description: `power` 375 376 * `*` `/` `%`: 377 Type: Binary 378 379 Associativity: Left 380 381 Description: `multiply`, `divide`, `modulus` 382 383 * `+` `-`: 384 Type: Binary 385 386 Associativity: Left 387 388 Description: `add`, `subtract` 389 390 * `<<` `>>`: 391 Type: Binary 392 393 Associativity: Left 394 395 Description: `shift left`, `shift right` 396 397 * `=` `<<=` `>>=` `+=` `-=` `*=` `/=` `%=` `^=` `@=`: 398 Type: Binary 399 400 Associativity: Right 401 402 Description: `assignment` 403 404 * `==` `<=` `>=` `!=` `<` `>`: 405 Type: Binary 406 407 Associativity: Left 408 409 Description: `relational` 410 411 * `&&`: 412 Type: Binary 413 414 Associativity: Left 415 416 Description: `boolean and` 417 418 * `||`: 419 Type: Binary 420 421 Associativity: Left 422 423 Description: `boolean or` 424 425The operators will be described in more detail below. 426 427<a name="bc-increment-decrement"/> 428 429 * `++` `--`: 430 The prefix and postfix `increment` and `decrement` operators behave exactly 431 like they would in C. They require a [named expression](#named-expressions) 432 as an operand. 433 434 * `-`: 435 The `negation` operator returns `0` if a user attempts to negate any 436 expression with the value `0`. Otherwise, a copy of the expression with its 437 sign flipped is returned. 438 439 * `!`: 440 The `boolean not` operator returns `1` if the expression is `0`, or `0` 441 otherwise. 442 443 This is a **non-portable extension**. 444 445 * `$`: 446 The `truncation` operator returns a copy of the given expression with all of 447 its **scale** removed. 448 449 This is a **non-portable extension**. 450 451 This is only available if bc(1) has been compiled with the extra math option 452 enabled. 453 454 * `@`: 455 The `set precision` operator takes two expressions and returns a copy of the 456 first with its **scale** equal to the value of the second expression. That 457 could either mean that the number is returned without change (if the 458 **scale** of the first expression matches the value of the second 459 expression), extended (if it is less), or truncated (if it is more). 460 461 The second expression must be an integer (no **scale**) and non-negative. 462 463 This is a **non-portable extension**. 464 465 This is only available if bc(1) has been compiled with the extra math option 466 enabled. 467 468 * `^`: 469 The `power` operator (not the `exclusive or` operator, as it would be in C) 470 takes two expressions and raises the first to the power of the value of the 471 second. 472 473 The second expression must be an integer (no **scale**), and if it is 474 negative, the first value must be non-zero. 475 476 * `*`: 477 The `multiply` operator takes two expressions, multiplies them, and returns 478 the product. If `a` is the **scale** of the first expression and `b` is the 479 **scale** of the second expression, the scale of the result is equal to 480 `min(a+b,max(scale,a,b))` where `min` and `max` return the obvious values. 481 482 * `/`: 483 The `divide` operator takes two expressions, divides them, and returns the 484 quotient. The scale of the result shall be the value of `scale`. 485 486 The second expression must be non-zero. 487 488 * `%`: 489 The `modulus` operator takes two expressions, `a` and `b`, and evaluates 490 them by 1) Computing `a/b` to current `scale` and 2) Using the result of 491 step 1 to calculate `a-(a/b)*b` to scale `max(scale+scale(b),scale(a))`. 492 493 The second expression must be non-zero. 494 495 * `+`: 496 The `add` operator takes two expressions, `a` and `b`, and returns the sum, 497 with a **scale** equal to the max of the **scale**s of `a` and `b`. 498 499 * `-`: 500 The `subtract` operator takes two expressions, `a` and `b`, and returns the 501 difference, with a **scale** equal to the max of the **scale**s of `a` and 502 `b`. 503 504 * `<<`: 505 The `left shift` operator takes two expressions, `a` and `b`, and returns a 506 copy of the value of `a` with its decimal point moved `b` places to the 507 right. 508 509 The second expression must be an integer (no **scale**) and non-negative. 510 511 This is a **non-portable extension**. 512 513 This is only available if bc(1) has been compiled with the extra math option 514 enabled. 515 516 * `>>`: 517 The `right shift` operator takes two expressions, `a` and `b`, and returns a 518 copy of the value of `a` with its decimal point moved `b` places to the 519 left. 520 521 The second expression must be an integer (no **scale**) and non-negative. 522 523 This is a **non-portable extension**. 524 525 This is only available if bc(1) has been compiled with the extra math option 526 enabled. 527 528<a name="bc-assignment"/> 529 530 * `=` `<<=` `>>=` `+=` `-=` `*=` `/=` `%=` `^=` `@=`: 531 The `assignment` operators take two expressions, `a` and `b` where `a` is a 532 [named expression](#bc-named-expressions). 533 534 For `=`, `b` is copied and the result is assigned to `a`. For all others, 535 `a` and `b` are applied as operands to the corresponding arithmetic 536 operator and the result is assigned to `a`. 537 538 The `assignment` operators that correspond to operators that are extensions 539 are themselves extensions. 540 541 Also, those `assignment` operators that are extensions are only available if 542 bc(1) has been compiled with the extra math option enabled. 543 544 * `==` `<=` `>=` `!=` `<` `>`: 545 The `relational` operators compare two expressions, `a` and `b`, and if the 546 relation holds, according to C language semantics, the result is `1`. 547 Otherwise, it is `0`. 548 549 Note that unlike in C, these operators have a lower precedence than the 550 `assignment` operators, which means that `a=b>c` is interpreted as 551 `(a=b)>c`. 552 553 Also, unlike the [standard][1] requires, these operators can appear anywhere 554 any other expressions can be used. This allowance is a 555 **non-portable extension**. 556 557 * `&&`: 558 The `boolean and` operator takes two expressions and returns `1` if both 559 expressions are non-zero, `0` otherwise. 560 561 This is ***not*** a short-circuit operator. 562 563 This is a **non-portable extension**. 564 565 * `||`: 566 The `boolean or` operator takes two expressions and returns `1` if one of 567 the expressions is non-zero, `0` otherwise. 568 569 This is ***not*** a short-circuit operator. 570 571 This is a **non-portable extension**. 572 573### Statements 574 575The following items are statements: 576 5771. `E` 5782. `{` `S` `;` ... `;` `S` `}` 5793. `if` `(` `E` `)` `S` 5804. `if` `(` `E` `)` `S` `else` `S` 5815. `while` `(` `E` `)` `S` 5826. `for` `(` `E` `;` `E` `;` `E` `)` `S` 5837. An empty statement 5848. `break` 5859. `continue` 58610. `quit` 58711. `halt` 58812. `limits` 58913. A string of characters, enclosed in double quotes 59014. `print` `E` `,` ... `,` `E` 59115. `I()`, `I(E)`, `I(E, E)`, and so on, where `I` is an identifier for a 592 [void function](#void-functions). The `E` parameters may also be arrays and 593 [array references](#array-references). 594 595Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. 596 597Also, as a **non-portable extension**, any or all of the expressions in the 598header of a for loop may be omitted. If the condition (second expression) is 599omitted, it is assumed to be a constant `1`. 600 601The `break` statement causes a loop to stop iterating and resume execution 602immediately following a loop. This is only allowed in loops. 603 604The `continue` statement causes a loop iteration to stop early and returns to 605the start of the loop, including testing the loop condition. This is only 606allowed in loops. 607 608The `if` `else` statement does the same thing as in C. 609 610The `quit` statement causes bc(1) to quit, even if it is on a branch that will 611not be executed (it is a compile-time command). 612 613The `halt` statement causes bc(1) to quit, if it is executed. (Unlike `quit` if 614it is on a branch of an `if` statement that is not executed, bc(1) does not 615quit.) 616 617The `limits` statement prints the limits that this bc(1) is subject to. This is 618like the `quit` statement in that it is a compile-time command. 619 620An expression by itself is evaluated and printed, followed by a newline. If 621bc(1) has been built with the extra math option enabled, both scientific 622notation and engineering notation are available for printing the results of 623expressions. Scientific notation is activated by assigning `0` to `obase` (in 624any other context, an `obase` of `0` is invalid), and engineering notation is 625activated by assigning `1` to `obase` (which is also invalid in any other 626context). To deactivate them, just assign a different value to `obase`. 627 628Scientific notation and engineering notation are disabled if bc(1) is run with 629either the `-s` or `-w` command-line options (or equivalents). 630 631Printing numbers in scientific notation and/or engineering notation is a 632**non-portable extension**. 633 634### Print Statement 635 636The "expressions" in a `print` statement may also be strings. If they are, there 637are backslash escape sequences that are interpreted specially. What those 638sequences are, and what they cause to be printed, are shown below: 639 640 * `\a`: 641 `\a` 642 643 * `\b`: 644 `\b` 645 646 * `\\`: 647 `\` 648 649 * `\e`: 650 `\` 651 652 * `\f`: 653 `\f` 654 655 * `\n`: 656 `\n` 657 658 * `\q`: 659 `"` 660 661 * `\r`: 662 `\r` 663 664 * `\t`: 665 `\t` 666 667Any other character following a backslash causes the backslash and character to 668be printed as-is. 669 670Any non-string expression in a print statement shall be assigned to `last`, like 671any other expression that is printed. 672 673### Order of Evaluation 674 675All expressions in a statment are evaluated left to right, except as necessary 676to maintain order of operations. This means, for example, that in the expression 677`i = 0; a[i++] = i++`, the first (or 0th) element of `a` is set to `1`, and `i` 678is equal to `2` at the end of the expression. 679 680This includes function arguments. Thus, this means that in the expression 681`i = 0; x(i++, i++)`, the first argument passed to `x()` is `0`, and the second 682argument is `1`, while `i` is equal to `2` before the function starts executing. 683 684FUNCTIONS 685--------- 686 687Function definitions are as follows: 688 689``` 690define I(I,...,I){ 691 auto I,...,I 692 S;...;S 693 return(E) 694} 695``` 696 697Any `I` in the parameter list or `auto` list may be replaced with `I[]` to make 698a parameter or `auto` var an array. 699 700As a **non-portable extension**, the opening brace of a `define` statement may 701appear on the next line. 702 703The return statement may also be in the following forms: 704 7051. `return` 7062. `return` `(` `)` 7073. `return` `E` 708 709The first two, or not specifying a `return` statement, is equivalent to 710`return (0)`, unless the function is a [void function](#void-functions). 711 712<a name="void-functions"/> 713 714### Void Functions 715 716Functions can also be void functions, defined as follows: 717 718``` 719define void I(I,...,I){ 720 auto I,...,I 721 S;...;S 722 return 723} 724``` 725 726They can only be used as standalone expressions, where such an expression would 727be printed alone, except in a print statement. 728 729Void functions can only use the first two `return` statements listed above. They 730can also omit the return statement entirely. 731 732The word `void` is not treated as a keyword; it is still possible to have 733variables, arrays, and functions named `void`. The word `void` is only treated 734specially right after the `define` keyword. 735 736This is a **non-portable extension**. 737 738<a name="array-references"/> 739 740### Array References 741 742For any array in the parameter list, if the array is declared in the form 743 744``` 745*I[] 746``` 747 748it is a **reference**. Any changes to the array in the function are reflected, 749when the function returns, to the array that was passed in. 750 751Other than this, all function arguments are passed by value. 752 753This is a **non-portable extension**. 754 755LIBRARY 756------- 757 758All of the functions below, including the functions in the 759[extended library](#extended-library) if bc(1) has been compiled with the extra 760math option enabled, are available when the `-l` or `--mathlib` command-line 761flags are given. 762 763<a name="standard-library"/> 764 765### Standard Library 766 767The [standard][1] defines the following functions for the math library: 768 769 * `s(x)`: 770 Returns the sine of `x`, which is assumed to be in radians. 771 772 This is a [transcendental function][5]. 773 774 * `c(x)`: 775 Returns the cosine of `x`, which is assumed to be in radians. 776 777 This is a [transcendental function][5]. 778 779 * `a(x)`: 780 Returns the arctangent of `x`, in radians. 781 782 This is a [transcendental function][5]. 783 784 * `l(x)`: 785 Returns the natural logarithm of `x`. 786 787 This is a [transcendental function][5]. 788 789 * `e(x)`: 790 Returns the mathematical constant `e` raised to the power of `x`. 791 792 This is a [transcendental function][5]. 793 794 * `j(x, n)`: 795 Returns the bessel integer order `n` (truncated) of `x`. 796 797 This is a [transcendental function][5]. 798 799<a name="extended-library"/> 800 801### Extended Library 802 803In addition to the [standard library](#standard-library), if bc(1) has been 804built with the extra math option, the following functions are available when 805either the `-l` or `--mathlib` options are given. 806 807However, the extended library is ***not*** loaded when the `-s`/`--standard` or 808`-w`/`--warn` options are given since they are not part of the library defined 809by the [standard][1]. 810 811The extended library is a **non-portable extension**. 812 813 * `r(x, p)`: 814 Returns `x` rounded to `p` decimal places according to the rounding mode 815 [round half away from `0`][3]. 816 817 * `ceil(x, p)`: 818 Returns `x` rounded to `p` decimal places according to the rounding mode 819 [round away from `0`][7]. 820 821 * `f(x)`: 822 Returns the factorial of the truncated absolute value of `x`. 823 824 * `perm(n, k)`: 825 Returns the permutation of the truncated absolute value of `n` of the 826 truncated absolute value of `k`, if `k <= n`. If not, it returns `0`. 827 828 * `comb(n, k)`: 829 Returns the combination of the truncated absolute value of `n` of the 830 truncated absolute value of `k`, if `k <= n`. If not, it returns `0`. 831 832 * `l2(x)`: 833 Returns the logarithm base `2` of `x`. 834 835 This is a [transcendental function][5]. 836 837 * `l10(x)`: 838 Returns the logarithm base `10` of `x`. 839 840 This is a [transcendental function][5]. 841 842 * `log(x, b)`: 843 Returns the logarithm base `b` of `x`. 844 845 This is a [transcendental function][5]. 846 847 * `cbrt(x)`: 848 Returns the cube root of `x`. 849 850 * `root(x, n)`: 851 Calculates the truncated value of `n`, `r`, and returns the `r`th root of 852 `x` to the current `scale`. 853 854 If `r` is `0` or negative, this raises an error and causes bc(1) to reset 855 (see the RESET section). It also raises an error and causes bc(1) to reset 856 if `r` is even and `x` is negative. 857 858 * `pi(p)`: 859 Returns `pi` to `p` decimal places. 860 861 This is a [transcendental function][5]. 862 863 * `t(x)`: 864 Returns the tangent of `x`, which is assumed to be in radians. 865 866 This is a [transcendental function][5]. 867 868 * `a2(y, x)`: 869 Returns the arctangent of `y/x`, in radians. If both `y` and `x` are equal 870 to `0`, it raises an error and causes bc(1) to reset (see the RESET 871 section). Otherwise, if `x` is greater than `0`, it returns `a(y/x)`. If `x` 872 is less than `0`, and `y` is greater than or equal to `0`, it returns 873 `a(y/x) + pi`. If `x` is less than `0`, and `y` is less than `0`, it returns 874 `a(y/x) - pi`. If `x` is equal to `0`, and `y` is greater than `0`, it 875 returns `pi/2`. If `x` is equal to `0`, and `y` is less than `0`, it returns 876 `-pi/2`. 877 878 This function is the same as the `atan2()` function in many programming 879 languages. 880 881 This is a [transcendental function][5]. 882 883 * `sin(x)`: 884 Returns the sine of `x`, which is assumed to be in radians. 885 886 This is an alias of `s(x)`. 887 888 This is a [transcendental function][5]. 889 890 * `cos(x)`: 891 Returns the cosine of `x`, which is assumed to be in radians. 892 893 This is an alias of `c(x)`. 894 895 This is a [transcendental function][5]. 896 897 * `tan(x)`: 898 Returns the tangent of `x`, which is assumed to be in radians. 899 900 If `x` is equal to `1` or `-1`, this raises an error and causes bc(1) to 901 reset (see the RESET section). 902 903 This is an alias of `t(x)`. 904 905 This is a [transcendental function][5]. 906 907 * `atan(x)`: 908 Returns the arctangent of `x`, in radians. 909 910 This is an alias of `a(x)`. 911 912 This is a [transcendental function][5]. 913 914 * `atan2(y, x)`: 915 Returns the arctangent of `y/x`, in radians. If both `y` and `x` are equal 916 to `0`, it raises an error and causes bc(1) to reset (see the RESET 917 section). Otherwise, if `x` is greater than `0`, it returns `a(y/x)`. If `x` 918 is less than `0`, and `y` is greater than or equal to `0`, it returns 919 `a(y/x) + pi`. If `x` is less than `0`, and `y` is less than `0`, it returns 920 `a(y/x) - pi`. If `x` is equal to `0`, and `y` is greater than `0`, it 921 returns `pi/2`. If `x` is equal to `0`, and `y` is less than `0`, it returns 922 `-pi/2`. 923 924 This function is the same as the `atan2()` function in many programming 925 languages. 926 927 This is an alias of `a2(y, x)`. 928 929 This is a [transcendental function][5]. 930 931 * `r2d(x)`: 932 Converts `x` from radians to degrees and returns the result. 933 934 This is a [transcendental function][5]. 935 936 * `d2r(x)`: 937 Converts `x` from degrees to radians and returns the result. 938 939 This is a [transcendental function][5]. 940 941 * `ubytes(x)`: 942 Returns the numbers of unsigned integer bytes required to hold the truncated 943 absolute value of `x`. 944 945 * `sbytes(x)`: 946 Returns the numbers of signed, two's-complement integer bytes required to 947 hold the truncated value of `x`. 948 949 * `hex(x)`: 950 Outputs the hexadecimal (base `16`) representation of `x`. 951 952 This is a [void function](#void-functions). 953 954 * `binary(x)`: 955 Outputs the binary (base `2`) representation of `x`. 956 957 This is a [void function](#void-functions). 958 959 * `output(x, b)`: 960 Outputs the base `b` representation of `x`. 961 962 This is a [void function](#void-functions). 963 964 * `uint(x)`: 965 Outputs the representation, in binary and hexadecimal, of `x` as an unsigned 966 integer in as few power of two bytes as possible. Both outputs are split 967 into bytes separated by spaces. 968 969 If `x` is not an integer or is negative, an error message is printed 970 instead, but bc(1) is not reset (see the RESET section). 971 972 This is a [void function](#void-functions). 973 974 * `int(x)`: 975 Outputs the representation, in binary and hexadecimal, of `x` as a signed, 976 two's-complement integer in as few power of two bytes as possible. Both 977 outputs are split into bytes separated by spaces. 978 979 If `x` is not an integer, an error message is printed instead, but bc(1) is 980 not reset (see the RESET section). 981 982 This is a [void function](#void-functions). 983 984 * `uintn(x, n)`: 985 Outputs the representation, in binary and hexadecimal, of `x` as an unsigned 986 integer in `n` bytes. Both outputs are split into bytes separated by spaces. 987 988 If `x` is not an integer, is negative, or cannot fit into `n` bytes, an 989 error message is printed instead, but bc(1) is not reset (see the RESET 990 section). 991 992 This is a [void function](#void-functions). 993 994 * `intn(x, n)`: 995 Outputs the representation, in binary and hexadecimal, of `x` as a signed, 996 two's-complement integer in `n` bytes. Both outputs are split into bytes 997 separated by spaces. 998 999 If `x` is not an integer or cannot fit into `n` bytes, an error message is 1000 printed instead, but bc(1) is not reset (see the RESET section). 1001 1002 This is a [void function](#void-functions). 1003 1004 * `uint8(x)`: 1005 Outputs the representation, in binary and hexadecimal, of `x` as an unsigned 1006 integer in `1` byte. Both outputs are split into bytes separated by spaces. 1007 1008 If `x` is not an integer, is negative, or cannot fit into `1` byte, an error 1009 message is printed instead, but bc(1) is not reset (see the RESET section). 1010 1011 This is a [void function](#void-functions). 1012 1013 * `int8(x)`: 1014 Outputs the representation, in binary and hexadecimal, of `x` as a signed, 1015 two's-complement integer in `1` byte. Both outputs are split into bytes 1016 separated by spaces. 1017 1018 If `x` is not an integer or cannot fit into `1` byte, an error message is 1019 printed instead, but bc(1) is not reset (see the RESET section). 1020 1021 This is a [void function](#void-functions). 1022 1023 * `uint16(x)`: 1024 Outputs the representation, in binary and hexadecimal, of `x` as an unsigned 1025 integer in `2` bytes. Both outputs are split into bytes separated by spaces. 1026 1027 If `x` is not an integer, is negative, or cannot fit into `2` bytes, an 1028 error message is printed instead, but bc(1) is not reset (see the RESET 1029 section). 1030 1031 This is a [void function](#void-functions). 1032 1033 * `int16(x)`: 1034 Outputs the representation, in binary and hexadecimal, of `x` as a signed, 1035 two's-complement integer in `2` bytes. Both outputs are split into bytes 1036 separated by spaces. 1037 1038 If `x` is not an integer or cannot fit into `2` bytes, an error message is 1039 printed instead, but bc(1) is not reset (see the RESET section). 1040 1041 This is a [void function](#void-functions). 1042 1043 * `uint32(x)`: 1044 Outputs the representation, in binary and hexadecimal, of `x` as an unsigned 1045 integer in `4` bytes. Both outputs are split into bytes separated by spaces. 1046 1047 If `x` is not an integer, is negative, or cannot fit into `4` bytes, an 1048 error message is printed instead, but bc(1) is not reset (see the RESET 1049 section). 1050 1051 This is a [void function](#void-functions). 1052 1053 * `int32(x)`: 1054 Outputs the representation, in binary and hexadecimal, of `x` as a signed, 1055 two's-complement integer in `4` bytes. Both outputs are split into bytes 1056 separated by spaces. 1057 1058 If `x` is not an integer or cannot fit into `4` bytes, an error message is 1059 printed instead, but bc(1) is not reset (see the RESET section). 1060 1061 This is a [void function](#void-functions). 1062 1063 * `uint64(x)`: 1064 Outputs the representation, in binary and hexadecimal, of `x` as an unsigned 1065 integer in `8` bytes. Both outputs are split into bytes separated by spaces. 1066 1067 If `x` is not an integer, is negative, or cannot fit into `8` bytes, an 1068 error message is printed instead, but bc(1) is not reset (see the RESET 1069 section). 1070 1071 This is a [void function](#void-functions). 1072 1073 * `int64(x)`: 1074 Outputs the representation, in binary and hexadecimal, of `x` as a signed, 1075 two's-complement integer in `8` bytes. Both outputs are split into bytes 1076 separated by spaces. 1077 1078 If `x` is not an integer or cannot fit into `8` bytes, an error message is 1079 printed instead, but bc(1) is not reset (see the RESET section). 1080 1081 This is a [void function](#void-functions). 1082 1083 * `hex_uint(x, n)`: 1084 Outputs the representation of the truncated absolute value of `x` as an 1085 unsigned integer in hexadecimal using `n` bytes. Not all of the value will 1086 be output if `n` is too small. 1087 1088 This is a [void function](#void-functions). 1089 1090 * `binary_uint(x, n)`: 1091 Outputs the representation of the truncated absolute value of `x` as an 1092 unsigned integer in binary using `n` bytes. Not all of the value will be 1093 output if `n` is too small. 1094 1095 This is a [void function](#void-functions). 1096 1097 * `output_uint(x, n)`: 1098 Outputs the representation of the truncated absolute value of `x` as an 1099 unsigned integer in the current [`obase`](#obase) using `n` bytes. Not all 1100 of the value will be output if `n` is too small. 1101 1102 This is a [void function](#void-functions). 1103 1104 * `output_byte(x, i)`: 1105 Outputs byte `i` of the truncated absolute value of `x`, where `0` is the 1106 least significant byte and `number_of_bytes - 1` is the most significant 1107 byte. 1108 1109 This is a [void function](#void-functions). 1110 1111<a name="transcendental-functions"/> 1112 1113### Transcendental Functions 1114 1115All transcendental functions can return slightly inaccurate results (up to 1 1116[ULP][4]). This is unavoidable, and [this article][6] explains why it is 1117impossible and unnecessary to calculate exact results for the transcendental 1118functions. 1119 1120Because of the possible inaccuracy, I recommend that users call those functions 1121with the precision (`scale`) set to at least 1 higher than is necessary. If 1122exact results are *absolutely* required, users can double the precision 1123(`scale`) and then truncate. 1124 1125The transcendental functions in the standard math library are: 1126 1127* `s(x)` 1128* `c(x)` 1129* `a(x)` 1130* `l(x)` 1131* `e(x)` 1132* `j(x, n)` 1133 1134The transcendental functions in the extended math library are: 1135 1136* `l2(x)` 1137* `l10(x)` 1138* `log(x, b)` 1139* `pi(p)` 1140* `t(x)` 1141* `a2(y, x)` 1142* `sin(x)` 1143* `cos(x)` 1144* `tan(x)` 1145* `atan(x)` 1146* `atan2(y, x)` 1147* `r2d(x)` 1148* `d2r(x)` 1149 1150RESET 1151----- 1152 1153When bc(1) encounters an error or a signal that it has a non-default handler 1154for, it resets. This means that several things happen. 1155 1156First, any functions that are executing are stopped and popped off the stack. 1157The behavior is not unlike that of exceptions in programming languages. Then 1158the execution point is set so that any code waiting to execute (after all 1159functions returned) is skipped. 1160 1161Thus, when bc(1) resets, it skips any remaining code waiting to be executed. 1162Then, if it is interactive mode, and the error was not a fatal error (see the 1163EXIT STATUS section), it asks for more input; otherwise, it exits with the 1164appropriate return code. 1165 1166Note that this reset behavior is different from the GNU bc(1), which attempts to 1167start executing the statement right after the one that caused an error. 1168 1169PERFORMANCE 1170----------- 1171 1172Most bc(1) implementations use `char` types to calculate the value of `1` 1173decimal digit at a time, but that can be slow. This bc(1) does something 1174different. 1175 1176It uses large integers to calculate more than `1` decimal digit at a time. If 1177built in a environment where `BC_LONG_BIT` (see the LIMITS section) is `64`, 1178then each integer has `9` decimal digits. If built in an environment where 1179`BC_LONG_BIT` is `32` then each integer has `4` decimal digits. This value (the 1180number of decimal digits per large integer) is called `BC_BASE_DIGS`. 1181 1182In addition, this bc(1) uses an even larger integer for overflow checking. This 1183integer type depends on the value of `BC_LONG_BIT`, but is always at least twice 1184as large as the integer type used to store digits. 1185 1186LIMITS 1187------ 1188 1189The following are the limits on bc(1): 1190 1191 * `BC_LONG_BIT`: 1192 The number of bits in the `long` type in the environment where bc(1) was 1193 built. This determines how many decimal digits can be stored in a single 1194 large integer (see the PERFORMANCE section). 1195 1196 * `BC_BASE_DIGS`: 1197 The number of decimal digits per large integer (see the PERFORMANCE 1198 section). Depends on `BC_LONG_BIT`. 1199 1200 * `BC_BASE_POW`: 1201 The max decimal number that each large integer can store (see 1202 `BC_BASE_DIGS`) plus `1`. Depends on `BC_BASE_DIGS`. 1203 1204 * `BC_OVERFLOW_MAX`: 1205 The max number that the overflow type (see the PERFORMANCE section) can 1206 hold. Depends on `BC_LONG_BIT`. 1207 1208 * `BC_BASE_MAX`: 1209 The maximum output base. Set at `BC_BASE_POW`. 1210 1211 * `BC_DIM_MAX`: 1212 The maximum size of arrays. Set at `SIZE_MAX-1`. 1213 1214 * `BC_SCALE_MAX`: 1215 The maximum `scale`. Set at `BC_OVERFLOW_MAX-1`. 1216 1217 * `BC_STRING_MAX`: 1218 The maximum length of strings. Set at `BC_OVERFLOW_MAX-1`. 1219 1220 * `BC_NAME_MAX`: 1221 The maximum length of identifiers. Set at `BC_OVERFLOW_MAX-1`. 1222 1223 * `BC_NUM_MAX`: 1224 The maximum length of a number (in decimal digits), which includes digits 1225 after the decimal point. Set at `BC_OVERFLOW_MAX-1`. 1226 1227 * Exponent: 1228 The maximum allowable exponent (positive or negative). Set at 1229 `BC_OVERFLOW_MAX`. 1230 1231 * Number of vars: 1232 The maximum number of vars/arrays. Set at `SIZE_MAX-1`. 1233 1234Actual values can be queried with the `limits` statement. 1235 1236These limits are meant to be effectively non-existent; the limits are so large 1237(at least on 64-bit machines) that there should not be any point at which they 1238become a problem. In fact, memory should be exhausted before these limits should 1239be hit. 1240 1241ENVIRONMENT VARIABLES 1242--------------------- 1243 1244bc(1) recognizes the following environment variables: 1245 1246 * `POSIXLY_CORRECT`: 1247 If this variable exists (no matter the contents), bc(1) behaves as if 1248 the `-s` option was given. 1249 1250 * `BC_ENV_ARGS`: 1251 This is another way to give command-line arguments to bc(1). They should be 1252 in the same format as all other command-line arguments. These are always 1253 processed first, so any files given in `BC_ENV_ARGS` will be processed 1254 before files given on the command-line. This gives the user the ability to 1255 set up "standard" options and files to be used at every invocation. The most 1256 useful thing for such files to contain would be useful functions that the 1257 user might want every time bc(1) runs. 1258 1259 * `BC_LINE_LENGTH`: 1260 If this environment variable exists and contains an integer that is greater 1261 than `1` and is less than `UINT16_MAX` (`2^16-1`), bc(1) will output lines 1262 to that length, including the backslash (`\`). The default line length is 1263 `70`. 1264 1265 * `BC_EXPR_EXIT`: 1266 If this variable exists (no matter the contents), bc(1) will exit 1267 immediately after executing expressions and files given by the `-e` and/or 1268 `-f` command-line options (and any equivalents). 1269 1270EXIT STATUS 1271----------- 1272 1273bc(1) returns the following exit statuses: 1274 1275 * `0`: 1276 No error. 1277 1278 * `1`: 1279 A math error occurred. This follows standard practice of using `1` for 1280 expected errors, since math errors will happen in the process of normal 1281 execution. 1282 1283 Math errors include divide by `0`, taking the square root of a negative 1284 number, attempting to convert a negative number to a hardware integer, 1285 overflow when converting a number to a hardware integer, and attempting to 1286 use a non-integer where an integer is required. 1287 1288 Converting to a hardware integer happens for the second operand of the power 1289 (`^`), places (`@`), left shift (`<<`), and right shift (`>>`) operators and 1290 their corresponding assignment operators. 1291 1292 * `2`: 1293 A parse error occurred. 1294 1295 Parse errors include unexpected `EOF`, using an invalid character, failing 1296 to find the end of a string or comment, using a token where it is invalid, 1297 giving an invalid expression, giving an invalid print statement, giving an 1298 invalid function definition, attempting to assign to an expression that is 1299 not a [named expression](#bc-named-expressions), giving an invalid `auto` 1300 list, having a duplicate `auto`/function parameter, failing to find the end 1301 of a code block, attempting to return a value from a `void` function, 1302 attempting to use a variable as a reference, and using any extensions when 1303 the option `-s` or any equivalents were given. 1304 1305 * `3`: 1306 A runtime error occurred. 1307 1308 Runtime errors include assigning an invalid number to `ibase`, `obase`, or 1309 `scale`; give a bad expression to a `read()` call, calling `read()` inside 1310 of a `read()` call, type errors, passing the wrong number of parameters to 1311 functions, attempting to call an undefined function, and attempting to use a 1312 `void` function call as a value in an expression. 1313 1314 * `4`: 1315 A fatal error occurred. 1316 1317 Fatal errors include memory allocation errors, I/O errors, failing to open 1318 files, attempting to use files that do not have only ASCII characters (bc(1) 1319 only accepts ASCII characters), attempting to open a directory as a file, 1320 and giving invalid command-line options. 1321 1322The exit status `4` is special; when a fatal error occurs, bc(1) always exits 1323and returns `4`, no matter what mode bc(1) is in. 1324 1325The other statuses will only be returned when bc(1) is not in interactive mode, 1326since bc(1) resets its state (see the RESET section) and accepts more input when 1327one of those errors occurs in interactive mode. This is also the case when 1328interactive mode is forced by the `-i` option. 1329 1330These exit statuses allow bc(1) to be used in shell scripting with error 1331checking, and its normal behavior can be forced by using `-i`. 1332 1333SIGNAL HANDLING 1334--------------- 1335 1336If bc(1) has been compiled with the signal handling, sending a `SIGINT` will 1337cause bc(1) to stop execution of the current input and reset (see the RESET 1338section), asking for more input. 1339 1340Otherwise, `SIGTERM` and `SIGQUIT` cause bc(1) to clean up and exit, and it uses 1341the default handler for all other signals. 1342 1343If bc(1) has not been compiled with signal handling, it uses the default signal 1344handlers for all signals. 1345 1346COMMAND LINE HISTORY 1347-------------------- 1348 1349bc(1) supports interactive command-line editing, if compiled with the history 1350option enabled. If `stdin` is hooked to a terminal, it is enabled. Previous 1351lines can be recalled and edited with the arrow keys. 1352 1353**Note**: when bc(1) is built with history support, tabs are converted to 8 1354spaces. 1355 1356LOCALES 1357------- 1358 1359This bc(1) ships with support for adding error messages for different locales. 1360 1361SEE ALSO 1362-------- 1363 1364dc(1) 1365 1366STANDARDS 1367--------- 1368 1369bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] 1370specification. The flags `-efghiqsvVw`, all long options, and the extensions 1371noted above are extensions to that specification. 1372 1373Note that the specification explicitly says that bc(1) only accepts numbers that 1374use a period (`.`) as a radix point, regardless of the value of `LC_NUMERIC`. 1375 1376This bc(1) ships with support for adding error messages for different locales, 1377so it supports `LC_MESSAGES`. 1378 1379AUTHOR 1380------ 1381 1382This bc(1) was made from scratch by Gavin D. Howard. 1383 1384BUGS 1385---- 1386 1387None are known. Report bugs at https://github.com/gavinhoward/bc. 1388 1389[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html 1390[2]: https://www.gnu.org/software/bc/ 1391[3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero 1392[4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place 1393[5]: #transcendental-functions 1394[6]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT 1395[7]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero 1396