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