BC(1P)

๐ŸŒธ BC(1P) ๐ŸŒธ

the POSIX Programmer's Manual, bestie edition ๐Ÿ’–

okay so real talk: this page lives in the POSIX Programmer's Manual. the Linux version of this interface might do stuff differently (so like, go read the matching Linux manual page if u wanna know what Linux is actually doing, fr), and honestly it might not even be implemented on Linux at all. ๐Ÿ™ˆ


โœจ NAME โœจ

bc โ€” arbitrary-precision arithmetic language ๐Ÿ’…


๐ŸŽ€ SYNOPSIS ๐ŸŽ€

bc [-l] [file...]

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

so bc is literally an arbitrary precision calculator and it's iconic for it. it takes input from whatever files u hand it, and then it reads from standard input. ๐Ÿซถ

and here's the tea: if both standard input AND standard output are attached to a terminal, then the invocation of bc counts as interactive, which means it picks up the behavioral constraints described in the sections below. main character energy tbh ๐Ÿ‘‘


๐Ÿ’… OPTIONS ๐Ÿ’…

bc shall conform to the Base Definitions volume of POSIX.1โ€2017, Section 12.2, Utility Syntax Guidelines. (yes queen, follow the rules โœจ)

the following option shall be supported:

  • -l โ€” (that's the letter ell, not a one, bestie ๐Ÿ˜ญ) define the math functions and initialize scale to 20, instead of the default zero. see the EXTENDED DESCRIPTION section for the whole story.

๐ŸŒธ OPERANDS ๐ŸŒธ

the following operand shall be supported:

  • file โ€” a pathname of a text file containing bc program statements. after all the files have been read, bc shall read the standard input. ๐Ÿ“‚

โญ STDIN โญ

see the INPUT FILES section. (yes it's giving "go look over there", i don't make the rules ๐Ÿ’€)


๐Ÿ“ INPUT FILES ๐Ÿ“

input files shall be text files containing a sequence of comments, statements, and function definitions that shall be executed as they are read. no cap, they run the second they're read ๐Ÿƒโ€โ™€๏ธ๐Ÿ’จ


๐ŸŒˆ ENVIRONMENT VARIABLES ๐ŸŒˆ

the following environment variables shall affect the execution of bc:

  • LANG โ€” provides a default value for the internationalization variables that are unset or null. (peep the Base Definitions volume of POSIX.1โ€2017, Section 8.2, Internationalization Variables for the precedence order of internationalization variables used to figure out the values of locale categories. iykyk โœจ)
  • LC_ALL โ€” if it's set to a non-empty string value, it overrides the values of ALL the other internationalization variables. it said "i'm the boss here" ๐Ÿ’…
  • LC_CTYPE โ€” determines the locale for interpreting sequences of bytes of text data as characters (like, single-byte vs multi-byte characters in arguments and input files). ๐Ÿงš
  • LC_MESSAGES โ€” determines the locale that should be used to affect the format and contents of diagnostic messages written to standard error. ๐Ÿ“ข
  • NLSPATH โ€” determines the location of message catalogs for the processing of LC_MESSAGES. ๐Ÿ—บ๏ธ

๐Ÿ”ฅ ASYNCHRONOUS EVENTS ๐Ÿ”ฅ

Default. (short king of a section, we love that for it ๐Ÿซถ)


๐Ÿ’– STDOUT ๐Ÿ’–

the output of the bc utility shall be controlled by the program it reads, and it consists of zero or more lines containing the value of all executed expressions without assignments. the radix and precision of the output shall be controlled by the values of the obase and scale variables โ€” see the EXTENDED DESCRIPTION section. ๐ŸŽ€


๐Ÿ’€ STDERR ๐Ÿ’€

standard error shall be used only for diagnostic messages. that's it. that's the whole vibe. ๐Ÿ™ˆ


๐ŸŽ€ OUTPUT FILES ๐ŸŽ€

None. (nothing to see here, moving on bestie โœจ)


๐Ÿ‘‘ EXTENDED DESCRIPTION ๐Ÿ‘‘

๐ŸŒธ Grammar ๐ŸŒธ

the grammar in this section and the lexical conventions in the next section shall together describe the syntax for bc programs. the general conventions for this style of grammar live in Section 1.3, Grammar Conventions. a valid program can be represented as the non-terminal symbol program in the grammar. and important: this formal syntax shall take precedence over the text syntax description. so if the vibes conflict, the grammar wins. periodt ๐Ÿ’…

%token    EOF NEWLINE STRING LETTER NUMBER

%token    MUL_OP
/*        '*', '/', '%'                           */

%token    ASSIGN_OP
/*        '=', '+=', '-=', '*=', '/=', '%=', '^=' */

%token    REL_OP
/*        '==', '<=', '>=', '!=', '<', '>'        */

%token    INCR_DECR
/*        '++', '--'                              */

%token    Define    Break    Quit    Length
/*        'define', 'break', 'quit', 'length'     */

%token    Return    For    If    While    Sqrt
/*        'return', 'for', 'if', 'while', 'sqrt'  */

%token    Scale    Ibase    Obase    Auto
/*        'scale', 'ibase', 'obase', 'auto'       */

%start    program

%%

program              : EOF
                     | input_item program
                     ;

input_item           : semicolon_list NEWLINE
                     | function
                     ;

semicolon_list       : /* empty */
                     | statement
                     | semicolon_list ';' statement
                     | semicolon_list ';'
                     ;

statement_list       : /* empty */
                     | statement
                     | statement_list NEWLINE
                     | statement_list NEWLINE statement
                     | statement_list ';'
                     | statement_list ';' statement
                     ;

statement            : expression
                     | STRING
                     | Break
                     | Quit
                     | Return
                     | Return '(' return_expression ')'
                     | For '(' expression ';'
                           relational_expression ';'
                           expression ')' statement
                     | If '(' relational_expression ')' statement
                     | While '(' relational_expression ')' statement
                     | '{' statement_list '}'
                     ;

function             : Define LETTER '(' opt_parameter_list ')'
                           '{' NEWLINE opt_auto_define_list
                           statement_list '}'
                     ;

opt_parameter_list   : /* empty */
                     | parameter_list
                     ;

parameter_list       : LETTER
                     | define_list ',' LETTER
                     ;

opt_auto_define_list : /* empty */
                     | Auto define_list NEWLINE
                     | Auto define_list ';'
                     ;

define_list          : LETTER
                     | LETTER '[' ']'
                     | define_list ',' LETTER
                     | define_list ',' LETTER '[' ']'
                     ;

opt_argument_list    : /* empty */
                     | argument_list
                     ;

argument_list        : expression
                     | LETTER '[' ']' ',' argument_list
                     ;

relational_expression : expression
                     | expression REL_OP expression
                     ;

return_expression    : /* empty */
                     | expression
                     ;

expression           : named_expression
                     | NUMBER
                     | '(' expression ')'
                     | LETTER '(' opt_argument_list ')'
                     | '-' expression
                     | expression '+' expression
                     | expression '-' expression
                     | expression MUL_OP expression
                     | expression '^' expression
                     | INCR_DECR named_expression
                     | named_expression INCR_DECR
                     | named_expression ASSIGN_OP expression
                     | Length '(' expression ')'
                     | Sqrt '(' expression ')'
                     | Scale '(' expression ')'
                     ;

named_expression     : LETTER
                     | LETTER '[' expression ']'
                     | Scale
                     | Ibase
                     | Obase
                     ;

๐Ÿ’œ Lexical Conventions in bc ๐Ÿ’œ

the lexical conventions for bc programs, relative to that grammar up there, shall be as follows. buckle up bestie, there's 8 of them ๐Ÿฆ‹

  1. except as noted, bc shall recognize the longest possible token or delimiter beginning at a given point. it's an overachiever, it takes everything it can get ๐Ÿ’…
  2. a comment shall consist of any characters beginning with the two adjacent characters "/*" and terminated by the next occurrence of the two adjacent characters "*/". comments shall have no effect except to delimit lexical tokens. (they're just there for the aesthetic โœจ)
  3. the <newline> shall be recognized as the token NEWLINE. ๐Ÿ“
  4. the token STRING shall represent a string constant; it shall consist of any characters beginning with the double-quote character ('"') and terminated by another occurrence of the double-quote character. the value of the string is the sequence of all characters between, but not including, the two double-quote characters. all characters shall be taken literally from the input, and there is no way to specify a string containing a double-quote character. ๐Ÿ˜ญ the length of the value of each string shall be limited to {BC_STRING_MAX} bytes.
  5. a <blank> shall have no effect except as an ordinary character if it appears within a STRING token, or to delimit a lexical token other than STRING. spaces said "i'm only here when it matters" ๐Ÿ™ˆ
  6. the combination of a <backslash> character immediately followed by a <newline> shall have no effect other than to delimit lexical tokens, with the following exceptions:
    • it shall be interpreted as the character sequence "\<newline>" in STRING tokens.
    • it shall be ignored as part of a multi-line NUMBER token.
  7. the token NUMBER shall represent a numeric constant. it shall be recognized by the following grammar:
NUMBER  : integer
        | '.' integer
        | integer '.'
        | integer '.' integer
        ;

integer : digit
        | integer digit
        ;

digit   : 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
        | 8 | 9 | A | B | C | D | E | F
        ;
  1. the value of a NUMBER token shall be interpreted as a numeral in the base specified by the value of the internal register ibase (described below). each of the digit characters shall have the value from 0 to 15 in the order listed right here โฌ†๏ธ, and the <period> character shall represent the radix point. โš ๏ธ the behavior is undefined if digits greater than or equal to the value of ibase appear in the token. however โ€” and this is important โ€” note the exception for single-digit values being assigned to ibase and obase themselves, over in Operations in bc. ๐Ÿ‘€
  2. These keywords are tokens, bestie, they run the whole show:
auto     ibase    length   return   while
break    if       obase    scale
define   for      quit     sqrt
  1. Any of these characters, showing up anywhere except inside a keyword, gets read as the token LETTER:
a b c d e f g h i j k l m n o p q r s t u v w x y z
  1. These single- and two-character sequences are the token ASSIGN_OP:
=   +=   -=   *=   /=   %=   ^=
  1. Okay heads up, this one's spicy: if an '=' character, as the beginning of a token, is followed by a '-' character with no delimiter in between, the behavior is undefined. No vibes, no rules, just chaos. ๐Ÿ™ˆ
  2. These single characters are the token MUL_OP:
*   /   %
  1. These single- and two-character sequences are the token REL_OP:
==   <=   >=   !=   <   >
  1. These two-character sequences are the token INCR_DECR:
++   --
  1. These single characters are tokens whose names are literally the character itself:
<newline>  (  )  ,  +  -  ;  [  ]  ^  {  }
  1. And the token EOF gets returned the moment you hit the end of input. bye bestie ๐Ÿ‘‹

๐Ÿงฎ Operations in bc ๐Ÿ’…

So there are three kinds of identifiers: ordinary identifiers, array identifiers, and function identifiers. All three types are made of single lowercase letters โ€” that's it, that's the whole alphabet of names, one letter each. ๐ŸŒธ

Array identifiers always get followed by square brackets ([]). You need an array subscript, except when you're in an argument list or an auto list. Arrays are singly dimensioned and can hold up to {BC_DIM_MAX} elements. Indexing starts at zero, so an array is indexed from 0 to {BC_DIM_MAX}-1. Subscripts get truncated to integers. And function identifiers have to be followed by parentheses, possibly with arguments inside. The three types of identifiers do not conflict โ€” they can all vibe in the same namespace, no drama.

Here's the whole precedence and associativity tea, laid out. Operators on the same line share a precedence level, and the rows go from highest precedence down to lowest:

Operator                     Associativity
++ , --                      N/A
unary -                      N/A
^                            Right to left
*, /, %                      Left to right
+, binary -                  Left to right
=, +=, -=, *=, /=, %=, ^=    Right to left
==, <=, >=, !=, <, >         None

Every expression, or named expression, has a scale โ€” that's the number of decimal digits that get maintained as the fractional part of the expression. It's like, how much precision are we keeping after the decimal point. โœจ

Named expressions are the places where values actually live. They're valid on the left side of an assignment. The value of a named expression is whatever's stored in the place it names. Simple identifiers and array elements are named expressions โ€” they start with an initial value of zero and an initial scale of zero. Blank slate, main character energy. ๐ŸŽ€

The internal registers scale, ibase, and obase are all named expressions too. The scale of an expression that's just the name of one of these registers is zero, and values you assign to any of these registers get truncated to integers. The scale register holds a global value used when computing the scale of expressions (more on that below). The value of the scale register is limited to 0 โ‰ค scale โ‰ค {BC_SCALE_MAX} and defaults to zero. The ibase and obase registers are the input and output number radix, respectively. The value of ibase is limited to:

2 โ‰ค ibase โ‰ค 16

and the value of obase is limited to:

2 โ‰ค obase โ‰ค {BC_BASE_MAX}

Now, when you assign either ibase or obase a single digit value from that list in Lexical Conventions in bc, the value is assumed to be in hexadecimal. (Like, ibase=A sets you to base ten, no matter what the current ibase value is. That's the point, it's the escape hatch. ๐Ÿซถ) Otherwise โ€” behavior is undefined when digits greater than or equal to the value of ibase show up in the input. Both ibase and obase start out at 10.

Internal computations happen as if in decimal, regardless of your input and output bases, carried out to the specified number of decimal digits. And when an exact result isn't achievable (for example, scale=0; 3.2/1), the result gets truncated. No rounding, no mercy. ๐Ÿ’…

For every value of obase that this volume of POSIX.1โ€2017 specifies, bc outputs numeric values by doing each of these steps, in order:

  1. If the value is less than zero, a <hyphen-minus> ('-') character gets output.
  2. Then one of these gets output, depending on the numerical value:
    • If the absolute value of the numerical value is greater than or equal to one, the integer portion gets output as a series of digits appropriate to obase (as described below), most significant digit first. The most significant non-zero digit comes out next, followed by each successively less significant digit.
    • If the absolute value of the numerical value is less than one but greater than zero, and the scale of the numerical value is greater than zero, it is unspecified whether the character 0 gets output. (Yes, unspecified. Nobody's promising you anything here. ๐Ÿ™ˆ)
    • If the numerical value is zero, the character 0 gets output.
  3. If the scale of the value is greater than zero and the numeric value is not zero, a <period> character gets output, followed by a series of digits appropriate to obase (as described below) representing the most significant portion of the fractional part of the value. If s represents the scale of the value being output, the number of digits output is s if obase is 10, less than or equal to s if obase is greater than 10, or greater than or equal to s if obase is less than 10. For obase values other than 10, this should be the number of digits needed to represent a precision of 10s.

For obase values from 2 to 16, the valid digits are the first obase of these single characters:

0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F

which represent the values zero to 15, inclusive, respectively. โญ

For bases greater than 16, each digit gets written as its own separate multi-digit decimal number. Every digit except the most significant fractional digit is preceded by a single <space>. For bases from 17 to 100, bc writes two-digit decimal numbers; for bases from 101 to 1000, three-digit decimal strings, and so on. So for example, the decimal number 1024 in base 25 gets written as:

01 15 24

and in base 125, as:

008 024

Very large numbers get split across lines with 70 characters per line in the POSIX locale; other locales may split at different character boundaries. Lines that are continued end with a <backslash>. ๐ŸŒˆ

A function call is a function name followed by parentheses containing a <comma>-separated list of expressions โ€” those are the function arguments. If you want to pass a whole array as an argument, you do it with the array name followed by empty square brackets. All function arguments are passed by value, bestie. So any changes made to the formal parameters have no effect on the actual arguments โ€” your originals are safe. ๐Ÿซถ If the function terminates by executing a return statement, the value of the function is the value of the expression inside the parentheses of the return statement, or zero if no expression is provided or if there's no return statement at all.

The result of sqrt(expression) is the square root of the expression. The result gets truncated in the least significant decimal place. The scale of the result is the scale of the expression or the value of scale, whichever is larger.

The result of length(expression) is the total number of significant decimal digits in the expression. The scale of the result is zero. โœจ

The result of scale(expression) is the scale of the expression. The scale of the result is zero. ๐Ÿ’…

A numeric constant is an expression. Its scale is the number of digits that follow the radix point in the input representing the constant, or zero if no radix point appears.

The sequence ( expression ) is an expression with the same value and scale as expression. The parentheses can be used to alter the normal precedence. (Group chat parenthesis, basically. ๐ŸŽ€)

Now the semantics of the unary and binary operators, one by one:

  • -expression โ€” The result is the negative of the expression. The scale of the result is the scale of expression.

The unary increment and decrement operators shall not modify the scale of the named expression they operate on. The scale of the result is the scale of that named expression.

  • ++named-expression โ€” The named expression gets incremented by one. The result is the value of the named expression after incrementing.
  • --named-expression โ€” The named expression gets decremented by one. The result is the value of the named expression after decrementing.
  • named-expression++ โ€” The named expression gets incremented by one. The result is the value of the named expression before incrementing.
  • named-expression-- โ€” The named expression gets decremented by one. The result is the value of the named expression before decrementing.

The exponentiation operator, <circumflex> ('^'), binds right to left.

  • expression^expression โ€” The result is the first expression raised to the power of the second expression. If the second expression is not an integer, the behavior is undefined. If a is the scale of the left expression and b is the absolute value of the right expression, the scale of the result is:
if b >= 0 min(a * b, max(scale, a)) if b < 0 scale

The multiplicative operators ('*', '/', '%') bind left to right.

  • expression*expression โ€” The result is the product of the two expressions. If a and b are the scales of the two expressions, then the scale of the result is:
min(a+b,max(scale,a,b))

๐ŸŒธ the operators, continued (yes there's more, stay with me) ๐ŸŒธ

  • expression/expression โ€” bestie, this is just division ๐Ÿ’… the result is the quotient of the two expressions, and the scale of that result is literally just whatever the value of scale is at the time.
  • expression%expression โ€” the mod operator, the remainder girlie ๐ŸŽ€ for expressions a and b, a%b gets evaluated like it's doing these exact steps, no cap:
    1. Compute a/b to current scale.
    2. Use that result to compute:
a - (a / b) * b

to scale:

max(scale + scale(b), scale(a))

and the scale of the result is:

max(scale + scale(b), scale(a))

fr fr when scale is zero, the '%' operator is literally just the mathematical remainder operator. iconic.


โž•โž– additive operators โž•โž–

These bad boys ('+', '-') bind left to right.

  • expression+expression โ€” the result is the sum of the two expressions, and its scale is the maximum of the scales of the two expressions. simple as that.
  • expression-expression โ€” the result is the difference of the two expressions, and again its scale is the maximum of the scales of the two expressions. slay.

โœจ assignment operators โœจ

The assignment operators ('=', "+=", "-=", "*=", "/=", "%=", "^=") bind right to left.

  • named-expression=expression โ€” this expression results in assigning the value of the expression on the right to the named expression on the left ๐Ÿซถ and the scale of both the named expression and the result is the scale of expression.

The compound assignment forms:

named-expression <operator>= expression

are equivalent to:

named-expression=named-expression <operator> expression
the one exception, bestie: the named-expression is only evaluated once. don't come for me.

๐Ÿ” relational operators ๐Ÿ”

Unlike every other operator, the relational operators ('<', '>', "<=", ">=", "==", "!=") are only valid as the object of an if, a while, or inside a for statement. that's the vibe check, they don't go anywhere else ๐Ÿ’€

  • expression1<expression2 โ€” true if the value of expression1 is strictly less than the value of expression2.
  • expression1>expression2 โ€” true if the value of expression1 is strictly greater than the value of expression2.
  • expression1<=expression2 โ€” true if the value of expression1 is less than or equal to the value of expression2.
  • expression1>=expression2 โ€” true if the value of expression1 is greater than or equal to the value of expression2.
  • expression1==expression2 โ€” true if the values of expression1 and expression2 are equal.
  • expression1!=expression2 โ€” true if the values of expression1 and expression2 are unequal.

๐Ÿ—„๏ธ storage classes, the tea โ˜•

There are only two storage classes in bc: global and automatic (local).

Only identifiers that are local to a function need to be declared with the auto command. The arguments to a function are local to the function. Every other identifier is assumed to be global and available to all functions ๐ŸŒˆ

All identifiers, global and local, start with initial values of zero. Identifiers declared as auto get allocated on entry to the function and released on return from the function โ€” so they don't keep their values between function calls, periodt.

Auto arrays get specified by the array name followed by empty square brackets. On entry to a function, the old values of the names that show up as parameters and as automatic variables get pushed onto a stack. Until the function returns, references to these names refer only to the new values.

References to any of these names from other functions called from this function also refer to the new value โ€” until one of those functions uses the same name for a local variable. iykyk.


๐Ÿ“ statements doing their thing ๐Ÿ“

When a statement is an expression, unless the main operator is an assignment, executing the statement writes the value of the expression followed by a <newline>.

When a statement is a string, executing the statement writes the value of the string. ๐Ÿ’ฌ

Statements separated by <semicolon> or <newline> characters get executed sequentially. In an interactive invocation of bc, every time a <newline> is read that satisfies this grammatical production:

input_item : semicolon_list NEWLINE

the sequential list of statements making up the semicolon_list gets executed immediately, and any output produced by that execution gets written with no delay due to buffering. no buffering lag bestie, we move fast โœจ


๐ŸŒ€ control flow girlies ๐ŸŒ€

In an if statement โ€” if(relation) statement โ€” the statement gets executed if the relation is true.

The while statement โ€” while(relation) statement โ€” implements a loop where the relation is tested; each time the relation is true, the statement gets executed and the relation gets retested. When the relation is false, execution resumes after statement.

A for statement โ€” for(expression; relation; expression) statement โ€” is the same as:

first-expression
while (relation) {
    statement
    last-expression
}
โš ๏ธ the application shall ensure that all three expressions are present. no skipping, bestie.

The break statement causes termination of a for or while statement. ๐Ÿ›‘


๐ŸŽ€ auto, define, return, quit ๐ŸŽ€

The auto statement โ€” auto identifier [,identifier] ... โ€” causes the values of the identifiers to be pushed down. The identifiers can be ordinary identifiers or array identifiers. Array identifiers get specified by following the array name by empty square brackets.

โš ๏ธ the application shall ensure that the auto statement is the first statement in a function definition. no exceptions ๐Ÿ’…

A define statement:

define LETTER ( opt_parameter_list ) {
    opt_auto_define_list
    statement_list
}

defines a function named LETTER. If a function named LETTER was already defined, the define statement replaces the previous definition. The expression:

LETTER ( opt_argument_list )

invokes the function named LETTER.

๐Ÿ’€ the behavior is undefined if the number of arguments in the invocation doesn't match the number of parameters in the definition.

Functions have to be defined before they're invoked. A function is considered to be defined within its own body, so recursive calls are valid ๐Ÿ” The values of numeric constants within a function get interpreted in the base specified by the value of the ibase register when the function is invoked.

The return statements (return and return(expression)) cause termination of a function, popping of its auto variables, and specification of the result of the function. The first form is equivalent to return(0). The value and scale of the result returned by the function is the value and scale of the expression returned.

The quit statement (quit) stops execution of a bc program at the point where the statement occurs in the input โ€” even if it occurs in a function definition, or in an if, for, or while statement. yeah, it's that powerful ๐Ÿ‘‘


๐Ÿงฎ the -l math functions ๐Ÿงฎ

These functions get defined when the -l option is specified:

  • s( expression ) โ€” sine of argument in radians ๐ŸŒŠ
  • c( expression ) โ€” cosine of argument in radians ๐ŸŒŠ
  • a( expression ) โ€” arctangent of argument.
  • l( expression ) โ€” natural logarithm of argument.
  • e( expression ) โ€” exponential function of argument.
  • j( expression1, expression2 ) โ€” Bessel function of expression2 of the first kind of integer order expression1.

The scale of the result returned by these functions is the value of the scale register at the time the function is invoked. The value of the scale register after these functions have completed their execution is the same value it had upon invocation โ€” they clean up after themselves, we love to see it ๐Ÿซถ

โš ๏ธ the behavior is undefined if any of these functions is invoked with an argument outside the domain of the mathematical function. don't do it bestie, it's giving chaos ๐Ÿ’€

โœจ EXIT STATUS โœจ

The following exit values shall be returned:

  • 0 โ€” all input files were processed successfully. ๐ŸŽ‰
  • unspecified โ€” an error occurred. ๐Ÿ˜ญ

๐Ÿ’ฅ CONSEQUENCES OF ERRORS ๐Ÿ’ฅ

If any file operand is specified and the named file can't be accessed, bc shall write a diagnostic message to standard error and terminate without any further action.

In an interactive invocation of bc, the utility should print an error message and recover following any error in the input ๐Ÿฉน In a non-interactive invocation of bc, invalid input causes undefined behavior.

The following sections are informative.

๐ŸŒˆ APPLICATION USAGE ๐ŸŒˆ

Automatic variables in bc do not work in exactly the same way as in either C or PL/1. ngl, they just don't.

For historical reasons, the exit status from bc cannot be relied upon to indicate that an error has occurred. Returning zero after an error is possible. So bc should be used primarily by interactive users (who can react to error messages) or by application programs that can somehow validate the answers returned as not including error messages. ๐Ÿ™ˆ

The bc utility always uses the <period> ('.') character to represent a radix point, regardless of any decimal-point character specified as part of the current locale. In languages like C or awk, the <period> character is used in program source, so it can be portable and unambiguous, while the locale-specific character is used in input and output. Because there's no distinction between source and input in bc, this arrangement wouldn't be possible. Using the locale-specific character in bc's input would introduce ambiguities into the language; consider the following example in a locale with a <comma> as the decimal-point character:

define f(a,b) {
    ...
}
...

f(1,2,3)

Because of such ambiguities, the <period> character is used in input. Having input follow different conventions from output would be confusing in either pipeline usage or interactive usage, so the <period> is also used in output. consistency queen ๐Ÿ‘‘

โœจ EXAMPLES โœจ

Okay bestie, real talk, let's see this thing do something cute. ๐ŸŽ€

In the shell, the following assigns an approximation of the first ten digits of 'ฯ€' to the variable x:

x=$(printf "%s\n" 'scale = 10; 104348/33215' | bc)

The following bc program prints the same approximation of 'ฯ€', with a label, to standard output:

scale = 10
"pi equals "
104348 / 33215

The following defines a function to compute an approximate value of the exponential function (note that such a function is predefined if the -l option is specified):

scale = 20
define e(x){
    auto a, b, c, i, s
    a = 1
    b = 1
    s = 1
    for (i = 1; 1 == 1; i++){
        a = a*x
        b = b*i
        c = a/b
        if (c == 0) {
             return(s)
        }
        s = s+c
    }
}

The following prints approximate values of the exponential function of the first ten integers:

for (i = 1; i <= 10; ++i) {
    e(i)
}

Like, look at her go ๐Ÿ’… she's doing math and everything.


๐Ÿง  RATIONALE ๐Ÿง 

Okay so this is the "why is it Like This" section and honestly? It's giving lore. ๐Ÿ“œ

The bc utility is implemented historically as a front-end processor for dc; dc was not selected to be part of this volume of POSIX.1โ€2017 because bc was thought to have a more intuitive programmatic interface. Current implementations that implement bc using dc are expected to be compliant.

The exit status for error conditions has been left unspecified for several reasons:

  • The bc utility is used in both interactive and non-interactive situations. Different exit codes may be appropriate for the two uses.
  • It is unclear when a non-zero exit should be given; divide-by-zero, undefined functions, and syntax errors are all possibilities.
  • It is not clear what utility the exit status has.
  • In the 4.3 BSD, System V, and Ninth Edition implementations, bc works in conjunction with dc. The dc utility is the parent, bc is the child. This was done to cleanly terminate bc if dc aborted.

The decision to have bc exit upon encountering an inaccessible input file is based on the belief that bc file1 file2 is used most often when at least file1 contains data/function declarations/initializations. Having bc continue with prerequisite files missing is probably not useful. There is no implication in the CONSEQUENCES OF ERRORS section that bc must check all its files for accessibility before opening any of them.

There was considerable debate on the appropriateness of the language accepted by bc. Several reviewers preferred to see either a pure subset of the C language or some changes to make the language more compatible with C. While the bc language has some obvious similarities to C, it has never claimed to be compatible with any version of C. An interpreter for a subset of C might be a very worthwhile utility, and it could potentially make bc obsolete. However, no such utility is known in historical practice, and it was not within the scope of this volume of POSIX.1โ€2017 to define such a language and utility. If and when they are defined, it may be appropriate to include them in a future version of this standard. This left the following alternatives:

  1. Exclude any calculator language from this volume of POSIX.1โ€2017.

The consensus of the standard developers was that a simple programmatic calculator language is very useful for both applications and interactive users. The only arguments for excluding any calculator were that it would become obsolete if and when a C-compatible one emerged, or that the absence would encourage the development of such a C-compatible one. These arguments did not sufficiently address the needs of current application developers.

  1. Standardize the historical dc, possibly with minor modifications.

The consensus of the standard developers was that dc is a fundamentally less usable language and that that would be far too severe a penalty for avoiding the issue of being similar to but incompatible with C.

  1. Standardize the historical bc, possibly with minor modifications.

This was the approach taken. Most of the proponents of changing the language would not have been satisfied until most or all of the incompatibilities with C were resolved. Since most of the changes considered most desirable would break historical applications and require significant modification to historical implementations, almost no modifications were made. The one significant modification that was made was the replacement of the historical bc assignment operators "=+", and so on, with the more modern "+=", and so on. The older versions are considered to be fundamentally flawed because of the lexical ambiguity in uses like a=-1.

In order to permit implementations to deal with backwards-compatibility as they see fit, the behavior of this one ambiguous construct was made undefined. (At least three implementations have been known to support this change already, so the degree of change involved should not be great.)

The '%' operator is the mathematical remainder operator when scale is zero. The behavior of this operator for other values of scale is from historical implementations of bc, and has been maintained for the sake of historical applications despite its non-intuitive nature.

Historical implementations permit setting ibase and obase to a broader range of values. This includes values less than 2, which were not seen as sufficiently useful to standardize. These implementations do not interpret input properly for values of ibase that are greater than 16. This is because numeric constants are recognized syntactically, rather than lexically, as described in this volume of POSIX.1โ€2017. They are built from lexical tokens of single hexadecimal digits and <period> characters. Since <blank> characters between tokens are not visible at the syntactic level, it is not possible to recognize the multi-digit ``digits'' used in the higher bases properly. The ability to recognize input in these bases was not considered useful enough to require modifying these implementations. Note that the recognition of numeric constants at the syntactic level is not a problem with conformance to this volume of POSIX.1โ€2017, as it does not impact the behavior of conforming applications (and correct bc programs). Historical implementations also accept input with all of the digits '0'-'9' and 'A'-'F' regardless of the value of ibase; since digits with value greater than or equal to ibase are not really appropriate, the behavior when they appear is undefined, except for the common case of:

ibase=8;
    /* Process in octal base. */
...
ibase=A
    /* Restore decimal base. */
๐Ÿ‘€ bestie heads up, "undefined" is doing a LOT of heavy lifting in that paragraph. Don't be cute with it.

In some historical implementations, if the expression to be written is an uninitialized array element, a leading <space> and/or up to four leading 0 characters may be output before the character zero. This behavior is considered a bug; it is unlikely that any currently conforming application relies on:

echo 'b[3]' | bc

returning 00000 rather than 0.

Exact calculation of the number of fractional digits to output for a given value in a base other than 10 can be computationally expensive. Historical implementations use a faster approximation, and this is permitted. Note that the requirements apply only to values of obase that this volume of POSIX.1โ€2017 requires implementations to support (in particular, not to 1, 0, or negative bases, if an implementation supports them as an extension).

Historical implementations of bc did not allow array parameters to be passed as the last parameter to a function. New implementations are encouraged to remove this restriction even though it is not required by the grammar.


๐Ÿ”ฎ FUTURE DIRECTIONS ๐Ÿ”ฎ

None.

Like... nothing. Zero. Empty set. The future said "no thoughts, head empty" ๐Ÿ’€ iconic honestly.


๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

  • Section 1.3, Grammar Conventions, awk
  • The Base Definitions volume of POSIX.1โ€2017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines

Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .


aaaand that's the whole page bestie, we ate and left no crumbs ๐Ÿ“โœจ this one came from IEEE/The Open Group, dated 2017, and it lives under the name BC(1P) ๐ŸŽ€ go forth and calculate, you main character ๐Ÿ’–

๐Ÿ“ฆ where this page comes from