1BC(1P) POSIX Programmer's Manual BC(1P)
2
3
4
6 This manual page is part of the POSIX Programmer's Manual. The Linux
7 implementation of this interface may differ (consult the corresponding
8 Linux manual page for details of Linux behavior), or the interface may
9 not be implemented on Linux.
10
12 bc — arbitrary-precision arithmetic language
13
15 bc [-l] [file...]
16
18 The bc utility shall implement an arbitrary precision calculator. It
19 shall take input from any files given, then read from the standard
20 input. If the standard input and standard output to bc are attached to
21 a terminal, the invocation of bc shall be considered to be interactive,
22 causing behavioral constraints described in the following sections.
23
25 The bc utility shall conform to the Base Definitions volume of
26 POSIX.1‐2017, Section 12.2, Utility Syntax Guidelines.
27
28 The following option shall be supported:
29
30 -l (The letter ell.) Define the math functions and initialize
31 scale to 20, instead of the default zero; see the EXTENDED
32 DESCRIPTION section.
33
35 The following operand shall be supported:
36
37 file A pathname of a text file containing bc program statements.
38 After all files have been read, bc shall read the standard
39 input.
40
42 See the INPUT FILES section.
43
45 Input files shall be text files containing a sequence of comments,
46 statements, and function definitions that shall be executed as they are
47 read.
48
50 The following environment variables shall affect the execution of bc:
51
52 LANG Provide a default value for the internationalization vari‐
53 ables that are unset or null. (See the Base Definitions vol‐
54 ume of POSIX.1‐2017, Section 8.2, Internationalization Vari‐
55 ables for the precedence of internationalization variables
56 used to determine the values of locale categories.)
57
58 LC_ALL If set to a non-empty string value, override the values of
59 all the other internationalization variables.
60
61 LC_CTYPE Determine the locale for the interpretation of sequences of
62 bytes of text data as characters (for example, single-byte as
63 opposed to multi-byte characters in arguments and input
64 files).
65
66 LC_MESSAGES
67 Determine the locale that should be used to affect the format
68 and contents of diagnostic messages written to standard
69 error.
70
71 NLSPATH Determine the location of message catalogs for the processing
72 of LC_MESSAGES.
73
75 Default.
76
78 The output of the bc utility shall be controlled by the program read,
79 and consist of zero or more lines containing the value of all executed
80 expressions without assignments. The radix and precision of the output
81 shall be controlled by the values of the obase and scale variables; see
82 the EXTENDED DESCRIPTION section.
83
85 The standard error shall be used only for diagnostic messages.
86
88 None.
89
91 Grammar
92 The grammar in this section and the lexical conventions in the follow‐
93 ing section shall together describe the syntax for bc programs. The
94 general conventions for this style of grammar are described in Section
95 1.3, Grammar Conventions. A valid program can be represented as the
96 non-terminal symbol program in the grammar. This formal syntax shall
97 take precedence over the text syntax description.
98
99
100 %token EOF NEWLINE STRING LETTER NUMBER
101
102 %token MUL_OP
103 /* '*', '/', '%' */
104
105 %token ASSIGN_OP
106 /* '=', '+=', '-=', '*=', '/=', '%=', '^=' */
107
108 %token REL_OP
109 /* '==', '<=', '>=', '!=', '<', '>' */
110
111 %token INCR_DECR
112 /* '++', '--' */
113
114 %token Define Break Quit Length
115 /* 'define', 'break', 'quit', 'length' */
116
117 %token Return For If While Sqrt
118 /* 'return', 'for', 'if', 'while', 'sqrt' */
119
120 %token Scale Ibase Obase Auto
121 /* 'scale', 'ibase', 'obase', 'auto' */
122
123 %start program
124
125 %%
126
127 program : EOF
128 | input_item program
129 ;
130
131 input_item : semicolon_list NEWLINE
132 | function
133 ;
134
135 semicolon_list : /* empty */
136 | statement
137 | semicolon_list ';' statement
138 | semicolon_list ';'
139 ;
140
141 statement_list : /* empty */
142 | statement
143 | statement_list NEWLINE
144 | statement_list NEWLINE statement
145 | statement_list ';'
146 | statement_list ';' statement
147 ;
148
149 statement : expression
150 | STRING
151 | Break
152 | Quit
153 | Return
154 | Return '(' return_expression ')'
155 | For '(' expression ';'
156 relational_expression ';'
157 expression ')' statement
158 | If '(' relational_expression ')' statement
159 | While '(' relational_expression ')' statement
160 | '{' statement_list '}'
161 ;
162
163 function : Define LETTER '(' opt_parameter_list ')'
164 '{' NEWLINE opt_auto_define_list
165 statement_list '}'
166 ;
167
168 opt_parameter_list : /* empty */
169 | parameter_list
170 ;
171
172 parameter_list : LETTER
173 | define_list ',' LETTER
174 ;
175
176 opt_auto_define_list : /* empty */
177 | Auto define_list NEWLINE
178 | Auto define_list ';'
179 ;
180
181 define_list : LETTER
182 | LETTER '[' ']'
183 | define_list ',' LETTER
184 | define_list ',' LETTER '[' ']'
185 ;
186
187 opt_argument_list : /* empty */
188 | argument_list
189 ;
190
191 argument_list : expression
192 | LETTER '[' ']' ',' argument_list
193 ;
194
195 relational_expression : expression
196 | expression REL_OP expression
197 ;
198
199 return_expression : /* empty */
200 | expression
201 ;
202
203 expression : named_expression
204 | NUMBER
205 | '(' expression ')'
206 | LETTER '(' opt_argument_list ')'
207 | '-' expression
208 | expression '+' expression
209 | expression '-' expression
210 | expression MUL_OP expression
211 | expression '^' expression
212 | INCR_DECR named_expression
213 | named_expression INCR_DECR
214 | named_expression ASSIGN_OP expression
215 | Length '(' expression ')'
216 | Sqrt '(' expression ')'
217 | Scale '(' expression ')'
218 ;
219
220 named_expression : LETTER
221 | LETTER '[' expression ']'
222 | Scale
223 | Ibase
224 | Obase
225 ;
226
227 Lexical Conventions in bc
228 The lexical conventions for bc programs, with respect to the preceding
229 grammar, shall be as follows:
230
231 1. Except as noted, bc shall recognize the longest possible token or
232 delimiter beginning at a given point.
233
234 2. A comment shall consist of any characters beginning with the two
235 adjacent characters "/*" and terminated by the next occurrence of
236 the two adjacent characters "*/". Comments shall have no effect
237 except to delimit lexical tokens.
238
239 3. The <newline> shall be recognized as the token NEWLINE.
240
241 4. The token STRING shall represent a string constant; it shall con‐
242 sist of any characters beginning with the double-quote character
243 ('"') and terminated by another occurrence of the double-quote
244 character. The value of the string is the sequence of all charac‐
245 ters between, but not including, the two double-quote characters.
246 All characters shall be taken literally from the input, and there
247 is no way to specify a string containing a double-quote character.
248 The length of the value of each string shall be limited to
249 {BC_STRING_MAX} bytes.
250
251 5. A <blank> shall have no effect except as an ordinary character if
252 it appears within a STRING token, or to delimit a lexical token
253 other than STRING.
254
255 6. The combination of a <backslash> character immediately followed by
256 a <newline> shall have no effect other than to delimit lexical
257 tokens with the following exceptions:
258
259 * It shall be interpreted as the character sequence "\<newline>"
260 in STRING tokens.
261
262 * It shall be ignored as part of a multi-line NUMBER token.
263
264 7. The token NUMBER shall represent a numeric constant. It shall be
265 recognized by the following grammar:
266
267
268 NUMBER : integer
269 | '.' integer
270 | integer '.'
271 | integer '.' integer
272 ;
273
274 integer : digit
275 | integer digit
276 ;
277
278 digit : 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
279 | 8 | 9 | A | B | C | D | E | F
280 ;
281
282 8. The value of a NUMBER token shall be interpreted as a numeral in
283 the base specified by the value of the internal register ibase
284 (described below). Each of the digit characters shall have the
285 value from 0 to 15 in the order listed here, and the <period> char‐
286 acter shall represent the radix point. The behavior is undefined if
287 digits greater than or equal to the value of ibase appear in the
288 token. However, note the exception for single-digit values being
289 assigned to ibase and obase themselves, in Operations in bc.
290
291 9. The following keywords shall be recognized as tokens:
292
293 auto ibase length return while
294 break if obase scale
295 define for quit sqrt
296
297 10. Any of the following characters occurring anywhere except within a
298 keyword shall be recognized as the token LETTER:
299
300
301 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
302
303 11. The following single-character and two-character sequences shall be
304 recognized as the token ASSIGN_OP:
305
306
307 = += -= *= /= %= ^=
308
309 12. If an '=' character, as the beginning of a token, is followed by a
310 '-' character with no intervening delimiter, the behavior is unde‐
311 fined.
312
313 13. The following single-characters shall be recognized as the token
314 MUL_OP:
315
316
317 * / %
318
319 14. The following single-character and two-character sequences shall be
320 recognized as the token REL_OP:
321
322
323 == <= >= != < >
324
325 15. The following two-character sequences shall be recognized as the
326 token INCR_DECR:
327
328
329 ++ --
330
331 16. The following single characters shall be recognized as tokens whose
332 names are the character:
333
334
335 <newline> ( ) , + - ; [ ] ^ { }
336
337 17. The token EOF is returned when the end of input is reached.
338
339 Operations in bc
340 There are three kinds of identifiers: ordinary identifiers, array iden‐
341 tifiers, and function identifiers. All three types consist of single
342 lowercase letters. Array identifiers shall be followed by square brack‐
343 ets ("[]"). An array subscript is required except in an argument or
344 auto list. Arrays are singly dimensioned and can contain up to
345 {BC_DIM_MAX} elements. Indexing shall begin at zero so an array is
346 indexed from 0 to {BC_DIM_MAX}-1. Subscripts shall be truncated to
347 integers. The application shall ensure that function identifiers are
348 followed by parentheses, possibly enclosing arguments. The three types
349 of identifiers do not conflict.
350
351 The following table summarizes the rules for precedence and associativ‐
352 ity of all operators. Operators on the same line shall have the same
353 precedence; rows are in order of decreasing precedence.
354
355 Table: Operators in bc
356
357 ┌──────────────────────────┬───────────────┐
358 │ Operator │ Associativity │
359 ├──────────────────────────┼───────────────┤
360 │++, -- │ N/A │
361 │unary - │ N/A │
362 │^ │ Right to left │
363 │*, /, % │ Left to right │
364 │+, binary - │ Left to right │
365 │=, +=, -=, *=, /=, %=, ^= │ Right to left │
366 │==, <=, >=, !=, <, > │ None │
367 └──────────────────────────┴───────────────┘
368 Each expression or named expression has a scale, which is the number of
369 decimal digits that shall be maintained as the fractional portion of
370 the expression.
371
372 Named expressions are places where values are stored. Named expressions
373 shall be valid on the left side of an assignment. The value of a named
374 expression shall be the value stored in the place named. Simple identi‐
375 fiers and array elements are named expressions; they have an initial
376 value of zero and an initial scale of zero.
377
378 The internal registers scale, ibase, and obase are all named expres‐
379 sions. The scale of an expression consisting of the name of one of
380 these registers shall be zero; values assigned to any of these regis‐
381 ters are truncated to integers. The scale register shall contain a
382 global value used in computing the scale of expressions (as described
383 below). The value of the register scale is limited to 0 ≤ scale ≤
384 {BC_SCALE_MAX} and shall have a default value of zero. The ibase and
385 obase registers are the input and output number radix, respectively.
386 The value of ibase shall be limited to:
387
388
389 2 ≤ ibase ≤ 16
390
391 The value of obase shall be limited to:
392
393
394 2 ≤ obase ≤ {BC_BASE_MAX}
395
396 When either ibase or obase is assigned a single digit value from the
397 list in Lexical Conventions in bc, the value shall be assumed in hexa‐
398 decimal. (For example, ibase=A sets to base ten, regardless of the cur‐
399 rent ibase value.) Otherwise, the behavior is undefined when digits
400 greater than or equal to the value of ibase appear in the input. Both
401 ibase and obase shall have initial values of 10.
402
403 Internal computations shall be conducted as if in decimal, regardless
404 of the input and output bases, to the specified number of decimal dig‐
405 its. When an exact result is not achieved (for example,
406 scale=0; 3.2/1), the result shall be truncated.
407
408 For all values of obase specified by this volume of POSIX.1‐2017, bc
409 shall output numeric values by performing each of the following steps
410 in order:
411
412 1. If the value is less than zero, a <hyphen-minus> ('-') character
413 shall be output.
414
415 2. One of the following is output, depending on the numerical value:
416
417 * If the absolute value of the numerical value is greater than or
418 equal to one, the integer portion of the value shall be output
419 as a series of digits appropriate to obase (as described
420 below), most significant digit first. The most significant non-
421 zero digit shall be output next, followed by each successively
422 less significant digit.
423
424 * If the absolute value of the numerical value is less than one
425 but greater than zero and the scale of the numerical value is
426 greater than zero, it is unspecified whether the character 0 is
427 output.
428
429 * If the numerical value is zero, the character 0 shall be out‐
430 put.
431
432 3. If the scale of the value is greater than zero and the numeric
433 value is not zero, a <period> character shall be output, followed
434 by a series of digits appropriate to obase (as described below)
435 representing the most significant portion of the fractional part of
436 the value. If s represents the scale of the value being output, the
437 number of digits output shall be s if obase is 10, less than or
438 equal to s if obase is greater than 10, or greater than or equal to
439 s if obase is less than 10. For obase values other than 10, this
440 should be the number of digits needed to represent a precision of
441 10s.
442
443 For obase values from 2 to 16, valid digits are the first obase of the
444 single characters:
445
446
447 0 1 2 3 4 5 6 7 8 9 A B C D E F
448
449 which represent the values zero to 15, inclusive, respectively.
450
451 For bases greater than 16, each digit shall be written as a separate
452 multi-digit decimal number. Each digit except the most significant
453 fractional digit shall be preceded by a single <space>. For bases from
454 17 to 100, bc shall write two-digit decimal numbers; for bases from 101
455 to 1000, three-digit decimal strings, and so on. For example, the deci‐
456 mal number 1024 in base 25 would be written as:
457
458
459 01 15 24
460
461 and in base 125, as:
462
463
464 008 024
465
466 Very large numbers shall be split across lines with 70 characters per
467 line in the POSIX locale; other locales may split at different charac‐
468 ter boundaries. Lines that are continued shall end with a <backslash>.
469
470 A function call shall consist of a function name followed by parenthe‐
471 ses containing a <comma>-separated list of expressions, which are the
472 function arguments. A whole array passed as an argument shall be speci‐
473 fied by the array name followed by empty square brackets. All function
474 arguments shall be passed by value. As a result, changes made to the
475 formal parameters shall have no effect on the actual arguments. If the
476 function terminates by executing a return statement, the value of the
477 function shall be the value of the expression in the parentheses of the
478 return statement or shall be zero if no expression is provided or if
479 there is no return statement.
480
481 The result of sqrt(expression) shall be the square root of the expres‐
482 sion. The result shall be truncated in the least significant decimal
483 place. The scale of the result shall be the scale of the expression or
484 the value of scale, whichever is larger.
485
486 The result of length(expression) shall be the total number of signifi‐
487 cant decimal digits in the expression. The scale of the result shall be
488 zero.
489
490 The result of scale(expression) shall be the scale of the expression.
491 The scale of the result shall be zero.
492
493 A numeric constant shall be an expression. The scale shall be the num‐
494 ber of digits that follow the radix point in the input representing the
495 constant, or zero if no radix point appears.
496
497 The sequence ( expression ) shall be an expression with the same value
498 and scale as expression. The parentheses can be used to alter the nor‐
499 mal precedence.
500
501 The semantics of the unary and binary operators are as follows:
502
503 -expression
504 The result shall be the negative of the expression. The scale of
505 the result shall be the scale of expression.
506
507 The unary increment and decrement operators shall not modify the scale
508 of the named expression upon which they operate. The scale of the
509 result shall be the scale of that named expression.
510
511 ++named-expression
512 The named expression shall be incremented by one. The result
513 shall be the value of the named expression after incrementing.
514
515 --named-expression
516 The named expression shall be decremented by one. The result
517 shall be the value of the named expression after decrementing.
518
519 named-expression++
520 The named expression shall be incremented by one. The result
521 shall be the value of the named expression before incrementing.
522
523 named-expression--
524 The named expression shall be decremented by one. The result
525 shall be the value of the named expression before decrementing.
526
527 The exponentiation operator, <circumflex> ('^'), shall bind right to
528 left.
529
530 expression^expression
531 The result shall be the first expression raised to the power of
532 the second expression. If the second expression is not an inte‐
533 ger, the behavior is undefined. If a is the scale of the left
534 expression and b is the absolute value of the right expression,
535 the scale of the result shall be:
536
537
538 if b >= 0 min(a * b, max(scale, a)) if b < 0 scale
539
540 The multiplicative operators ('*', '/', '%') shall bind left to right.
541
542 expression*expression
543 The result shall be the product of the two expressions. If a and
544 b are the scales of the two expressions, then the scale of the
545 result shall be:
546
547
548 min(a+b,max(scale,a,b))
549
550 expression/expression
551 The result shall be the quotient of the two expressions. The
552 scale of the result shall be the value of scale.
553
554 expression%expression
555 For expressions a and b, a%b shall be evaluated equivalent to the
556 steps:
557
558 1. Compute a/b to current scale.
559
560 2. Use the result to compute:
561
562
563 a - (a / b) * b
564
565 to scale:
566
567
568 max(scale + scale(b), scale(a))
569
570 The scale of the result shall be:
571
572
573 max(scale + scale(b), scale(a))
574
575 When scale is zero, the '%' operator is the mathematical remain‐
576 der operator.
577
578 The additive operators ('+', '-') shall bind left to right.
579
580 expression+expression
581 The result shall be the sum of the two expressions. The scale of
582 the result shall be the maximum of the scales of the expressions.
583
584 expression-expression
585 The result shall be the difference of the two expressions. The
586 scale of the result shall be the maximum of the scales of the
587 expressions.
588
589 The assignment operators ('=', "+=", "-=", "*=", "/=", "%=", "^=")
590 shall bind right to left.
591
592 named-expression=expression
593 This expression shall result in assigning the value of the
594 expression on the right to the named expression on the left. The
595 scale of both the named expression and the result shall be the
596 scale of expression.
597
598 The compound assignment forms:
599
600
601 named-expression <operator>= expression
602
603 shall be equivalent to:
604
605
606 named-expression=named-expression <operator> expression
607
608 except that the named-expression shall be evaluated only once.
609
610 Unlike all other operators, the relational operators ('<', '>', "<=",
611 ">=", "==", "!=") shall be only valid as the object of an if, while, or
612 inside a for statement.
613
614 expression1<expression2
615 The relation shall be true if the value of expression1 is
616 strictly less than the value of expression2.
617
618 expression1>expression2
619 The relation shall be true if the value of expression1 is
620 strictly greater than the value of expression2.
621
622 expression1<=expression2
623 The relation shall be true if the value of expression1 is less
624 than or equal to the value of expression2.
625
626 expression1>=expression2
627 The relation shall be true if the value of expression1 is greater
628 than or equal to the value of expression2.
629
630 expression1==expression2
631 The relation shall be true if the values of expression1 and
632 expression2 are equal.
633
634 expression1!=expression2
635 The relation shall be true if the values of expression1 and
636 expression2 are unequal.
637
638 There are only two storage classes in bc: global and automatic (local).
639 Only identifiers that are local to a function need be declared with the
640 auto command. The arguments to a function shall be local to the func‐
641 tion. All other identifiers are assumed to be global and available to
642 all functions. All identifiers, global and local, have initial values
643 of zero. Identifiers declared as auto shall be allocated on entry to
644 the function and released on returning from the function. They there‐
645 fore do not retain values between function calls. Auto arrays shall be
646 specified by the array name followed by empty square brackets. On entry
647 to a function, the old values of the names that appear as parameters
648 and as automatic variables shall be pushed onto a stack. Until the
649 function returns, reference to these names shall refer only to the new
650 values.
651
652 References to any of these names from other functions that are called
653 from this function also refer to the new value until one of those func‐
654 tions uses the same name for a local variable.
655
656 When a statement is an expression, unless the main operator is an
657 assignment, execution of the statement shall write the value of the
658 expression followed by a <newline>.
659
660 When a statement is a string, execution of the statement shall write
661 the value of the string.
662
663 Statements separated by <semicolon> or <newline> characters shall be
664 executed sequentially. In an interactive invocation of bc, each time a
665 <newline> is read that satisfies the grammatical production:
666
667
668 input_item : semicolon_list NEWLINE
669
670 the sequential list of statements making up the semicolon_list shall be
671 executed immediately and any output produced by that execution shall be
672 written without any delay due to buffering.
673
674 In an if statement (if(relation) statement), the statement shall be
675 executed if the relation is true.
676
677 The while statement (while(relation) statement) implements a loop in
678 which the relation is tested; each time the relation is true, the
679 statement shall be executed and the relation retested. When the rela‐
680 tion is false, execution shall resume after statement.
681
682 A for statement(for(expression; relation; expression) statement) shall
683 be the same as:
684
685
686 first-expression
687 while (relation) {
688 statement
689 last-expression
690 }
691
692 The application shall ensure that all three expressions are present.
693
694 The break statement shall cause termination of a for or while state‐
695 ment.
696
697 The auto statement (auto identifier [,identifier] ...) shall cause the
698 values of the identifiers to be pushed down. The identifiers can be
699 ordinary identifiers or array identifiers. Array identifiers shall be
700 specified by following the array name by empty square brackets. The
701 application shall ensure that the auto statement is the first statement
702 in a function definition.
703
704 A define statement:
705
706
707 define LETTER ( opt_parameter_list ) {
708 opt_auto_define_list
709 statement_list
710 }
711
712 defines a function named LETTER. If a function named LETTER was previ‐
713 ously defined, the define statement shall replace the previous defini‐
714 tion. The expression:
715
716
717 LETTER ( opt_argument_list )
718
719 shall invoke the function named LETTER. The behavior is undefined if
720 the number of arguments in the invocation does not match the number of
721 parameters in the definition. Functions shall be defined before they
722 are invoked. A function shall be considered to be defined within its
723 own body, so recursive calls are valid. The values of numeric constants
724 within a function shall be interpreted in the base specified by the
725 value of the ibase register when the function is invoked.
726
727 The return statements (return and return(expression)) shall cause ter‐
728 mination of a function, popping of its auto variables, and specifica‐
729 tion of the result of the function. The first form shall be equivalent
730 to return(0). The value and scale of the result returned by the func‐
731 tion shall be the value and scale of the expression returned.
732
733 The quit statement (quit) shall stop execution of a bc program at the
734 point where the statement occurs in the input, even if it occurs in a
735 function definition, or in an if, for, or while statement.
736
737 The following functions shall be defined when the -l option is speci‐
738 fied:
739
740 s( expression )
741 Sine of argument in radians.
742
743 c( expression )
744 Cosine of argument in radians.
745
746 a( expression )
747 Arctangent of argument.
748
749 l( expression )
750 Natural logarithm of argument.
751
752 e( expression )
753 Exponential function of argument.
754
755 j( expression1, expression2 )
756 Bessel function of expression2 of the first kind of integer order
757 expression1.
758
759 The scale of the result returned by these functions shall be the value
760 of the scale register at the time the function is invoked. The value of
761 the scale register after these functions have completed their execution
762 shall be the same value it had upon invocation. The behavior is unde‐
763 fined if any of these functions is invoked with an argument outside the
764 domain of the mathematical function.
765
767 The following exit values shall be returned:
768
769 0 All input files were processed successfully.
770
771 unspecified
772 An error occurred.
773
775 If any file operand is specified and the named file cannot be accessed,
776 bc shall write a diagnostic message to standard error and terminate
777 without any further action.
778
779 In an interactive invocation of bc, the utility should print an error
780 message and recover following any error in the input. In a non-interac‐
781 tive invocation of bc, invalid input causes undefined behavior.
782
783 The following sections are informative.
784
786 Automatic variables in bc do not work in exactly the same way as in
787 either C or PL/1.
788
789 For historical reasons, the exit status from bc cannot be relied upon
790 to indicate that an error has occurred. Returning zero after an error
791 is possible. Therefore, bc should be used primarily by interactive
792 users (who can react to error messages) or by application programs that
793 can somehow validate the answers returned as not including error mes‐
794 sages.
795
796 The bc utility always uses the <period> ('.') character to represent a
797 radix point, regardless of any decimal-point character specified as
798 part of the current locale. In languages like C or awk, the <period>
799 character is used in program source, so it can be portable and unam‐
800 biguous, while the locale-specific character is used in input and out‐
801 put. Because there is no distinction between source and input in bc,
802 this arrangement would not be possible. Using the locale-specific char‐
803 acter in bc's input would introduce ambiguities into the language; con‐
804 sider the following example in a locale with a <comma> as the decimal-
805 point character:
806
807
808 define f(a,b) {
809 ...
810 }
811 ...
812
813 f(1,2,3)
814
815 Because of such ambiguities, the <period> character is used in input.
816 Having input follow different conventions from output would be confus‐
817 ing in either pipeline usage or interactive usage, so the <period> is
818 also used in output.
819
821 In the shell, the following assigns an approximation of the first ten
822 digits of 'π' to the variable x:
823
824
825 x=$(printf "%s\n" 'scale = 10; 104348/33215' | bc)
826
827 The following bc program prints the same approximation of 'π', with a
828 label, to standard output:
829
830
831 scale = 10
832 "pi equals "
833 104348 / 33215
834
835 The following defines a function to compute an approximate value of the
836 exponential function (note that such a function is predefined if the -l
837 option is specified):
838
839
840 scale = 20
841 define e(x){
842 auto a, b, c, i, s
843 a = 1
844 b = 1
845 s = 1
846 for (i = 1; 1 == 1; i++){
847 a = a*x
848 b = b*i
849 c = a/b
850 if (c == 0) {
851 return(s)
852 }
853 s = s+c
854 }
855 }
856
857 The following prints approximate values of the exponential function of
858 the first ten integers:
859
860
861 for (i = 1; i <= 10; ++i) {
862 e(i)
863 }
864
866 The bc utility is implemented historically as a front-end processor for
867 dc; dc was not selected to be part of this volume of POSIX.1‐2017
868 because bc was thought to have a more intuitive programmatic interface.
869 Current implementations that implement bc using dc are expected to be
870 compliant.
871
872 The exit status for error conditions has been left unspecified for sev‐
873 eral reasons:
874
875 * The bc utility is used in both interactive and non-interactive sit‐
876 uations. Different exit codes may be appropriate for the two uses.
877
878 * It is unclear when a non-zero exit should be given; divide-by-zero,
879 undefined functions, and syntax errors are all possibilities.
880
881 * It is not clear what utility the exit status has.
882
883 * In the 4.3 BSD, System V, and Ninth Edition implementations, bc
884 works in conjunction with dc. The dc utility is the parent, bc is
885 the child. This was done to cleanly terminate bc if dc aborted.
886
887 The decision to have bc exit upon encountering an inaccessible input
888 file is based on the belief that bc file1 file2 is used most often when
889 at least file1 contains data/function declarations/initializations.
890 Having bc continue with prerequisite files missing is probably not use‐
891 ful. There is no implication in the CONSEQUENCES OF ERRORS section that
892 bc must check all its files for accessibility before opening any of
893 them.
894
895 There was considerable debate on the appropriateness of the language
896 accepted by bc. Several reviewers preferred to see either a pure sub‐
897 set of the C language or some changes to make the language more compat‐
898 ible with C. While the bc language has some obvious similarities to C,
899 it has never claimed to be compatible with any version of C. An inter‐
900 preter for a subset of C might be a very worthwhile utility, and it
901 could potentially make bc obsolete. However, no such utility is known
902 in historical practice, and it was not within the scope of this volume
903 of POSIX.1‐2017 to define such a language and utility. If and when they
904 are defined, it may be appropriate to include them in a future version
905 of this standard. This left the following alternatives:
906
907 1. Exclude any calculator language from this volume of POSIX.1‐2017.
908
909 The consensus of the standard developers was that a simple program‐
910 matic calculator language is very useful for both applications and
911 interactive users. The only arguments for excluding any calculator
912 were that it would become obsolete if and when a C-compatible one
913 emerged, or that the absence would encourage the development of
914 such a C-compatible one. These arguments did not sufficiently
915 address the needs of current application developers.
916
917 2. Standardize the historical dc, possibly with minor modifications.
918
919 The consensus of the standard developers was that dc is a fundamen‐
920 tally less usable language and that that would be far too severe a
921 penalty for avoiding the issue of being similar to but incompatible
922 with C.
923
924 3. Standardize the historical bc, possibly with minor modifications.
925
926 This was the approach taken. Most of the proponents of changing the
927 language would not have been satisfied until most or all of the
928 incompatibilities with C were resolved. Since most of the changes
929 considered most desirable would break historical applications and
930 require significant modification to historical implementations,
931 almost no modifications were made. The one significant modification
932 that was made was the replacement of the historical bc assignment
933 operators "=+", and so on, with the more modern "+=", and so on.
934 The older versions are considered to be fundamentally flawed
935 because of the lexical ambiguity in uses like a=-1.
936
937 In order to permit implementations to deal with backwards-compati‐
938 bility as they see fit, the behavior of this one ambiguous con‐
939 struct was made undefined. (At least three implementations have
940 been known to support this change already, so the degree of change
941 involved should not be great.)
942
943 The '%' operator is the mathematical remainder operator when scale is
944 zero. The behavior of this operator for other values of scale is from
945 historical implementations of bc, and has been maintained for the sake
946 of historical applications despite its non-intuitive nature.
947
948 Historical implementations permit setting ibase and obase to a broader
949 range of values. This includes values less than 2, which were not seen
950 as sufficiently useful to standardize. These implementations do not
951 interpret input properly for values of ibase that are greater than 16.
952 This is because numeric constants are recognized syntactically, rather
953 than lexically, as described in this volume of POSIX.1‐2017. They are
954 built from lexical tokens of single hexadecimal digits and <period>
955 characters. Since <blank> characters between tokens are not visible at
956 the syntactic level, it is not possible to recognize the multi-digit
957 ``digits'' used in the higher bases properly. The ability to recognize
958 input in these bases was not considered useful enough to require modi‐
959 fying these implementations. Note that the recognition of numeric con‐
960 stants at the syntactic level is not a problem with conformance to this
961 volume of POSIX.1‐2017, as it does not impact the behavior of conform‐
962 ing applications (and correct bc programs). Historical implementations
963 also accept input with all of the digits '0'-'9' and 'A'-'F' regardless
964 of the value of ibase; since digits with value greater than or equal to
965 ibase are not really appropriate, the behavior when they appear is
966 undefined, except for the common case of:
967
968
969 ibase=8;
970 /* Process in octal base. */
971 ...
972 ibase=A
973 /* Restore decimal base. */
974
975 In some historical implementations, if the expression to be written is
976 an uninitialized array element, a leading <space> and/or up to four
977 leading 0 characters may be output before the character zero. This
978 behavior is considered a bug; it is unlikely that any currently con‐
979 forming application relies on:
980
981
982 echo 'b[3]' | bc
983
984 returning 00000 rather than 0.
985
986 Exact calculation of the number of fractional digits to output for a
987 given value in a base other than 10 can be computationally expensive.
988 Historical implementations use a faster approximation, and this is per‐
989 mitted. Note that the requirements apply only to values of obase that
990 this volume of POSIX.1‐2017 requires implementations to support (in
991 particular, not to 1, 0, or negative bases, if an implementation sup‐
992 ports them as an extension).
993
994 Historical implementations of bc did not allow array parameters to be
995 passed as the last parameter to a function. New implementations are
996 encouraged to remove this restriction even though it is not required by
997 the grammar.
998
1000 None.
1001
1003 Section 1.3, Grammar Conventions, awk
1004
1005 The Base Definitions volume of POSIX.1‐2017, Chapter 8, Environment
1006 Variables, Section 12.2, Utility Syntax Guidelines
1007
1009 Portions of this text are reprinted and reproduced in electronic form
1010 from IEEE Std 1003.1-2017, Standard for Information Technology -- Por‐
1011 table Operating System Interface (POSIX), The Open Group Base Specifi‐
1012 cations Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of
1013 Electrical and Electronics Engineers, Inc and The Open Group. In the
1014 event of any discrepancy between this version and the original IEEE and
1015 The Open Group Standard, the original IEEE and The Open Group Standard
1016 is the referee document. The original Standard can be obtained online
1017 at http://www.opengroup.org/unix/online.html .
1018
1019 Any typographical or formatting errors that appear in this page are
1020 most likely to have been introduced during the conversion of the source
1021 files to man page format. To report such errors, see https://www.ker‐
1022 nel.org/doc/man-pages/reporting_bugs.html .
1023
1024
1025
1026IEEE/The Open Group 2017 BC(1P)