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