1BC(1P)                     POSIX Programmer's Manual                    BC(1P)
2
3
4

PROLOG

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
11

NAME

13       bc — arbitrary-precision arithmetic language
14

SYNOPSIS

16       bc [−l] [file...]
17

DESCRIPTION

19       The bc utility shall implement an arbitrary  precision  calculator.  It
20       shall  take  input  from  any  files given, then read from the standard
21       input. If the standard input and standard output to bc are attached  to
22       a terminal, the invocation of bc shall be considered to be interactive,
23       causing behavioral constraints described in the following sections.
24

OPTIONS

26       The bc  utility  shall  conform  to  the  Base  Definitions  volume  of
27       POSIX.1‐2008, Section 12.2, Utility Syntax Guidelines.
28
29       The following option shall be supported:
30
31       −l        (The  letter  ell.)  Define the math functions and initialize
32                 scale to 20, instead of the default zero;  see  the  EXTENDED
33                 DESCRIPTION section.
34

OPERANDS

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

STDIN

43       See the INPUT FILES section.
44

INPUT FILES

46       Input  files  shall  be  text  files containing a sequence of comments,
47       statements, and function definitions that shall be executed as they are
48       read.
49

ENVIRONMENT VARIABLES

51       The following environment variables shall affect the execution of bc:
52
53       LANG      Provide  a  default  value for the internationalization vari‐
54                 ables that are unset or null. (See the Base Definitions  vol‐
55                 ume  of POSIX.1‐2008, Section 8.2, Internationalization Vari‐
56                 ables for the precedence  of  internationalization  variables
57                 used to determine the values of locale categories.)
58
59       LC_ALL    If  set  to  a non-empty string value, override the values of
60                 all the other internationalization variables.
61
62       LC_CTYPE  Determine the locale for the interpretation of  sequences  of
63                 bytes of text data as characters (for example, single-byte as
64                 opposed to  multi-byte  characters  in  arguments  and  input
65                 files).
66
67       LC_MESSAGES
68                 Determine the locale that should be used to affect the format
69                 and contents  of  diagnostic  messages  written  to  standard
70                 error.
71
72       NLSPATH   Determine the location of message catalogs for the processing
73                 of LC_MESSAGES.
74

ASYNCHRONOUS EVENTS

76       Default.
77

STDOUT

79       The output of the bc utility shall be controlled by the  program  read,
80       and  consist of zero or more lines containing the value of all executed
81       expressions without assignments. The radix and precision of the  output
82       shall be controlled by the values of the obase and scale variables; see
83       the EXTENDED DESCRIPTION section.
84

STDERR

86       The standard error shall be used only for diagnostic messages.
87

OUTPUT FILES

89       None.
90

EXTENDED DESCRIPTION

92   Grammar
93       The grammar in this section and the lexical conventions in the  follow‐
94       ing  section  shall  together  describe the syntax for bc programs. The
95       general conventions for this style of grammar are described in  Section
96       1.3,  Grammar  Conventions.   A valid program can be represented as the
97       non-terminal symbol program in the grammar. This  formal  syntax  shall
98       take precedence over the text syntax description.
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               NUMBER  : integer
268                       | '.' integer
269                       | integer '.'
270                       | integer '.' integer
271                       ;
272
273               integer : digit
274                       | integer digit
275                       ;
276
277               digit   : 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
278                       | 8 | 9 | A | B | C | D | E | F
279                       ;
280
281        8. The value of a NUMBER token shall be interpreted as  a  numeral  in
282           the  base  specified  by  the  value of the internal register ibase
283           (described below). Each of the  digit  characters  shall  have  the
284           value from 0 to 15 in the order listed here, and the <period> char‐
285           acter shall represent the radix point. The behavior is undefined if
286           digits  greater  than  or equal to the value of ibase appear in the
287           token. However, note the exception for  single-digit  values  being
288           assigned to ibase and obase themselves, in Operations in bc.
289
290        9. The following keywords shall be recognized as tokens:
291
292           auto     ibase    length   return   while
293           break    if       obase    scale
294           define   for      quit     sqrt
295
296       10. Any  of the following characters occurring anywhere except within a
297           keyword shall be recognized as the token LETTER:
298
299               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
300
301       11. The following single-character and two-character sequences shall be
302           recognized as the token ASSIGN_OP:
303
304               =   +=   −=   *=   /=   %=   ^=
305
306       12. If  an '=' character, as the beginning of a token, is followed by a
307           '−' character with no intervening delimiter, the behavior is  unde‐
308           fined.
309
310       13. The  following  single-characters  shall be recognized as the token
311           MUL_OP:
312
313               *   /   %
314
315       14. The following single-character and two-character sequences shall be
316           recognized as the token REL_OP:
317
318               ==   <=   >=   !=   <   >
319
320       15. The  following  two-character  sequences shall be recognized as the
321           token INCR_DECR:
322
323               ++   −−
324
325       16. The following single characters shall be recognized as tokens whose
326           names are the character:
327
328               <newline>  (  )  ,  +  −  ;  [  ]  ^  {  }
329
330       17. The token EOF is returned when the end of input is reached.
331
332   Operations in bc
333       There are three kinds of identifiers: ordinary identifiers, array iden‐
334       tifiers, and function identifiers.  All three types consist  of  single
335       lowercase letters. Array identifiers shall be followed by square brack‐
336       ets ("[]").  An array subscript is required except in  an  argument  or
337       auto  list.   Arrays  are  singly  dimensioned  and  can  contain up to
338       {BC_DIM_MAX} elements. Indexing shall begin at  zero  so  an  array  is
339       indexed  from  0  to  {BC_DIM_MAX}−1.  Subscripts shall be truncated to
340       integers. The application shall ensure that  function  identifiers  are
341       followed  by parentheses, possibly enclosing arguments. The three types
342       of identifiers do not conflict.
343
344       The following table summarizes the rules for precedence and associativ‐
345       ity  of  all  operators. Operators on the same line shall have the same
346       precedence; rows are in order of decreasing precedence.
347
348                               Table: Operators in bc
349
350                     ┌──────────────────────────┬───────────────┐
351Operator          Associativity 
352                     ├──────────────────────────┼───────────────┤
353                     │++, −−                    │ N/A           │
354                     │unary −                   │ N/A           │
355                     │^                         │ Right to left │
356                     │*, /, %                   │ Left to right │
357                     │+, binary −               │ Left to right │
358                     │=, +=, −=, *=, /=, %=, ^= │ Right to left │
359                     │==, <=, >=, !=, <, >      │ None          │
360                     └──────────────────────────┴───────────────┘
361       Each expression or named expression has a scale, which is the number of
362       decimal  digits  that  shall be maintained as the fractional portion of
363       the expression.
364
365       Named expressions are places where values are stored. Named expressions
366       shall  be valid on the left side of an assignment. The value of a named
367       expression shall be the value stored in the place named. Simple identi‐
368       fiers  and  array  elements are named expressions; they have an initial
369       value of zero and an initial scale of zero.
370
371       The internal registers scale, ibase, and obase are  all  named  expres‐
372       sions.  The  scale  of  an  expression consisting of the name of one of
373       these registers shall be zero; values assigned to any of  these  regis‐
374       ters  are  truncated  to  integers.  The scale register shall contain a
375       global value used in computing the scale of expressions  (as  described
376       below).  The  value  of  the  register  scale is limited to 0 ≤ scale 
377       {BC_SCALE_MAX} and shall have a default value of zero.  The  ibase  and
378       obase  registers  are  the input and output number radix, respectively.
379       The value of ibase shall be limited to:
380
381           2 ≤ ibase ≤ 16
382
383       The value of obase shall be limited to:
384
385           2 ≤ obase ≤ {BC_BASE_MAX}
386
387       When either ibase or obase is assigned a single digit  value  from  the
388       list  in Lexical Conventions in bc, the value shall be assumed in hexa‐
389       decimal. (For example, ibase=A sets to base ten, regardless of the cur‐
390       rent  ibase  value.)  Otherwise,  the behavior is undefined when digits
391       greater than or equal to the value of ibase appear in the  input.  Both
392       ibase and obase shall have initial values of 10.
393
394       Internal  computations  shall be conducted as if in decimal, regardless
395       of the input and output bases, to the specified number of decimal  dig‐
396       its.   When   an   exact   result   is   not   achieved  (for  example,
397       scale=0; 3.2/1), the result shall be truncated.
398
399       For all values of obase specified by this volume  of  POSIX.1‐2008,  bc
400       shall  output  numeric values by performing each of the following steps
401       in order:
402
403        1. If the value is less than zero, a <hyphen> ('−') character shall be
404           output.
405
406        2. One of the following is output, depending on the numerical value:
407
408            *  If the absolute value of the numerical value is greater than or
409               equal to one, the integer portion of the value shall be  output
410               as  a  series  of  digits  appropriate  to  obase (as described
411               below), most significant digit first. The most significant non-
412               zero  digit shall be output next, followed by each successively
413               less significant digit.
414
415            *  If the absolute value of the numerical value is less  than  one
416               but  greater  than zero and the scale of the numerical value is
417               greater than zero, it is unspecified whether the character 0 is
418               output.
419
420            *  If  the  numerical value is zero, the character 0 shall be out‐
421               put.
422
423        3. If the scale of the value is greater  than  zero  and  the  numeric
424           value  is  not zero, a <period> character shall be output, followed
425           by a series of digits appropriate to  obase  (as  described  below)
426           representing the most significant portion of the fractional part of
427           the value. If s represents the scale of the value being output, the
428           number  of  digits  output  shall be s if obase is 10, less than or
429           equal to s if obase is greater than 10, or greater than or equal to
430           s  if  obase  is less than 10. For obase values other than 10, this
431           should be the number of digits needed to represent a  precision  of
432           10s.
433
434       For  obase values from 2 to 16, valid digits are the first obase of the
435       single characters:
436
437           0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F
438
439       which represent the values zero to 15, inclusive, respectively.
440
441       For bases greater than 16, each digit shall be written  as  a  separate
442       multi-digit  decimal  number.  Each  digit  except the most significant
443       fractional digit shall be preceded by a single <space>.  For bases from
444       17 to 100, bc shall write two-digit decimal numbers; for bases from 101
445       to 1000, three-digit decimal strings, and so on. For example, the deci‐
446       mal number 1024 in base 25 would be written as:
447
448            01 15 24
449
450       and in base 125, as:
451
452            008 024
453
454       Very  large  numbers shall be split across lines with 70 characters per
455       line in the POSIX locale; other locales may split at different  charac‐
456       ter boundaries. Lines that are continued shall end with a <backslash>.
457
458       A  function call shall consist of a function name followed by parenthe‐
459       ses containing a <comma>-separated list of expressions, which  are  the
460       function arguments. A whole array passed as an argument shall be speci‐
461       fied by the array name followed by empty square brackets. All  function
462       arguments  shall  be  passed by value. As a result, changes made to the
463       formal parameters shall have no effect on the actual arguments. If  the
464       function  terminates  by executing a return statement, the value of the
465       function shall be the value of the expression in the parentheses of the
466       return  statement  or  shall be zero if no expression is provided or if
467       there is no return statement.
468
469       The result of sqrt(expression) shall be the square root of the  expres‐
470       sion.  The  result  shall be truncated in the least significant decimal
471       place. The scale of the result shall be the scale of the expression  or
472       the value of scale, whichever is larger.
473
474       The  result of length(expression) shall be the total number of signifi‐
475       cant decimal digits in the expression. The scale of the result shall be
476       zero.
477
478       The  result  of scale(expression) shall be the scale of the expression.
479       The scale of the result shall be zero.
480
481       A numeric constant shall be an expression. The scale shall be the  num‐
482       ber of digits that follow the radix point in the input representing the
483       constant, or zero if no radix point appears.
484
485       The sequence ( expression ) shall be an expression with the same  value
486       and scale as expression.  The parentheses can be used to alter the nor‐
487       mal precedence.
488
489       The semantics of the unary and binary operators are as follows:
490
491expression
492             The result shall be the negative of the expression.  The scale of
493             the result shall be the scale of expression.
494
495       The  unary increment and decrement operators shall not modify the scale
496       of the named expression upon which  they  operate.  The  scale  of  the
497       result shall be the scale of that named expression.
498
499       ++named-expression
500             The  named  expression  shall  be  incremented by one. The result
501             shall be the value of the named expression after incrementing.
502
503       −−named-expression
504             The named expression shall be  decremented  by  one.  The  result
505             shall be the value of the named expression after decrementing.
506
507       named-expression++
508             The  named  expression  shall  be  incremented by one. The result
509             shall be the value of the named expression before incrementing.
510
511       named-expression−−
512             The named expression shall be  decremented  by  one.  The  result
513             shall be the value of the named expression before decrementing.
514
515       The  exponentiation  operator,  <circumflex> ('^'), shall bind right to
516       left.
517
518       expression^expression
519             The result shall be the first expression raised to the  power  of
520             the  second expression.  If the second expression is not an inte‐
521             ger, the behavior is undefined.  If a is the scale  of  the  left
522             expression  and  b is the absolute value of the right expression,
523             the scale of the result shall be:
524
525                 if b >= 0 min(a * b, max(scale, a)) if b < 0 scale
526
527       The multiplicative operators ('*', '/', '%') shall bind left to right.
528
529       expression*expression
530             The result shall be the product of the two expressions. If a  and
531             b  are  the  scales of the two expressions, then the scale of the
532             result shall be:
533
534                 min(a+b,max(scale,a,b))
535
536       expression/expression
537             The result shall be the quotient  of  the  two  expressions.  The
538             scale of the result shall be the value of scale.
539
540       expression%expression
541             For expressions a and b, a%b shall be evaluated equivalent to the
542             steps:
543
544              1. Compute a/b to current scale.
545
546              2. Use the result to compute:
547
548                     a − (a / b) * b
549
550                 to scale:
551
552                     max(scale + scale(b), scale(a))
553
554             The scale of the result shall be:
555
556                 max(scale + scale(b), scale(a))
557
558             When scale is zero, the '%' operator is the mathematical  remain‐
559             der operator.
560
561       The additive operators ('+', '−') shall bind left to right.
562
563       expression+expression
564             The  result shall be the sum of the two expressions. The scale of
565             the result shall be the maximum of the scales of the expressions.
566
567       expressionexpression
568             The result shall be the difference of the  two  expressions.  The
569             scale  of  the  result  shall be the maximum of the scales of the
570             expressions.
571
572       The assignment operators ('=', "+=",  "−=",  "*=",  "/=",  "%=",  "^=")
573       shall bind right to left.
574
575       named-expression=expression
576             This  expression  shall  result  in  assigning  the  value of the
577             expression on the right to the named expression on the left.  The
578             scale  of  both  the named expression and the result shall be the
579             scale of expression.
580
581       The compound assignment forms:
582
583           named-expression <operator>= expression
584
585       shall be equivalent to:
586
587           named-expression=named-expression <operator> expression
588
589       except that the named-expression shall be evaluated only once.
590
591       Unlike all other operators, the relational operators ('<',  '>',  "<=",
592       ">=", "==", "!=") shall be only valid as the object of an if, while, or
593       inside a for statement.
594
595       expression1<expression2
596             The relation shall  be  true  if  the  value  of  expression1  is
597             strictly less than the value of expression2.
598
599       expression1>expression2
600             The  relation  shall  be  true  if  the  value  of expression1 is
601             strictly greater than the value of expression2.
602
603       expression1<=expression2
604             The relation shall be true if the value of  expression1  is  less
605             than or equal to the value of expression2.
606
607       expression1>=expression2
608             The relation shall be true if the value of expression1 is greater
609             than or equal to the value of expression2.
610
611       expression1==expression2
612             The relation shall be true  if  the  values  of  expression1  and
613             expression2 are equal.
614
615       expression1!=expression2
616             The  relation  shall  be  true  if  the values of expression1 and
617             expression2 are unequal.
618
619       There are only two storage classes in bc: global and automatic (local).
620       Only identifiers that are local to a function need be declared with the
621       auto command. The arguments to a function shall be local to  the  func‐
622       tion.   All other identifiers are assumed to be global and available to
623       all functions. All identifiers, global and local, have  initial  values
624       of  zero.  Identifiers  declared as auto shall be allocated on entry to
625       the function and released on returning from the function.  They  there‐
626       fore  do not retain values between function calls. Auto arrays shall be
627       specified by the array name followed by empty square brackets. On entry
628       to  a  function,  the old values of the names that appear as parameters
629       and as automatic variables shall be pushed  onto  a  stack.  Until  the
630       function  returns, reference to these names shall refer only to the new
631       values.
632
633       References to any of these names from other functions that  are  called
634       from this function also refer to the new value until one of those func‐
635       tions uses the same name for a local variable.
636
637       When a statement is an expression,  unless  the  main  operator  is  an
638       assignment,  execution  of  the  statement shall write the value of the
639       expression followed by a <newline>.
640
641       When a statement is a string, execution of the  statement  shall  write
642       the value of the string.
643
644       Statements  separated  by  <semicolon> or <newline> characters shall be
645       executed sequentially. In an interactive invocation of bc, each time  a
646       <newline> is read that satisfies the grammatical production:
647
648           input_item : semicolon_list NEWLINE
649
650       the sequential list of statements making up the semicolon_list shall be
651       executed immediately and any output produced by that execution shall be
652       written without any delay due to buffering.
653
654       In  an  if  statement  (if(relation) statement), the statement shall be
655       executed if the relation is true.
656
657       The while statement (while(relation) statement) implements  a  loop  in
658       which  the  relation  is  tested;  each  time the relation is true, the
659       statement shall be executed and the relation retested. When  the  rela‐
660       tion is false, execution shall resume after statement.
661
662       A  for statement(for(expression; relation; expression) statement) shall
663       be the same as:
664
665           first-expression
666           while (relation) {
667               statement
668               last-expression
669           }
670
671       The application shall ensure that all three expressions are present.
672
673       The break statement shall cause termination of a for  or  while  state‐
674       ment.
675
676       The  auto statement (auto identifier [,identifier] ...) shall cause the
677       values of the identifiers to be pushed down.  The  identifiers  can  be
678       ordinary  identifiers  or array identifiers. Array identifiers shall be
679       specified by following the array name by  empty  square  brackets.  The
680       application shall ensure that the auto statement is the first statement
681       in a function definition.
682
683       A define statement:
684
685           define LETTER ( opt_parameter_list ) {
686               opt_auto_define_list
687               statement_list
688           }
689
690       defines a function named LETTER.  If a function named LETTER was previ‐
691       ously  defined, the define statement shall replace the previous defini‐
692       tion. The expression:
693
694           LETTER ( opt_argument_list )
695
696       shall invoke the function named LETTER.  The behavior is  undefined  if
697       the  number of arguments in the invocation does not match the number of
698       parameters in the definition. Functions shall be  defined  before  they
699       are  invoked.  A  function shall be considered to be defined within its
700       own body, so recursive calls are valid. The values of numeric constants
701       within  a  function  shall  be interpreted in the base specified by the
702       value of the ibase register when the function is invoked.
703
704       The return statements (return and return(expression)) shall cause  ter‐
705       mination  of  a function, popping of its auto variables, and specifica‐
706       tion of the result of the function. The first form shall be  equivalent
707       to  return(0).  The value and scale of the result returned by the func‐
708       tion shall be the value and scale of the expression returned.
709
710       The quit statement (quit) shall stop execution of a bc program  at  the
711       point  where  the statement occurs in the input, even if it occurs in a
712       function definition, or in an if, for, or while statement.
713
714       The following functions shall be defined when the −l option  is  speci‐
715       fied:
716
717       s( expression )
718             Sine of argument in radians.
719
720       c( expression )
721             Cosine of argument in radians.
722
723       a( expression )
724             Arctangent of argument.
725
726       l( expression )
727             Natural logarithm of argument.
728
729       e( expression )
730             Exponential function of argument.
731
732       j( expression, expression )
733             Bessel function of integer order.
734
735       The  scale of the result returned by these functions shall be the value
736       of the scale register at the time the function is invoked. The value of
737       the scale register after these functions have completed their execution
738       shall be the same value it had upon invocation. The behavior  is  unde‐
739       fined if any of these functions is invoked with an argument outside the
740       domain of the mathematical function.
741

EXIT STATUS

743       The following exit values shall be returned:
744
745       0         All input files were processed successfully.
746
747       unspecified
748                 An error occurred.
749

CONSEQUENCES OF ERRORS

751       If any file operand is specified and the named file cannot be accessed,
752       bc  shall  write  a  diagnostic message to standard error and terminate
753       without any further action.
754
755       In an interactive invocation of bc, the utility should print  an  error
756       message and recover following any error in the input. In a non-interac‐
757       tive invocation of bc, invalid input causes undefined behavior.
758
759       The following sections are informative.
760

APPLICATION USAGE

762       Automatic variables in bc do not work in exactly the  same  way  as  in
763       either C or PL/1.
764
765       For  historical  reasons, the exit status from bc cannot be relied upon
766       to indicate that an error has occurred.  Returning zero after an  error
767       is  possible.  Therefore,  bc  should  be used primarily by interactive
768       users (who can react to error messages) or by application programs that
769       can  somehow  validate the answers returned as not including error mes‐
770       sages.
771
772       The bc utility always uses the <period> ('.')  character to represent a
773       radix  point,  regardless  of  any decimal-point character specified as
774       part of the current locale. In languages like C or  awk,  the  <period>
775       character  is  used  in program source, so it can be portable and unam‐
776       biguous, while the locale-specific character is used in input and  out‐
777       put.  Because  there  is no distinction between source and input in bc,
778       this arrangement would not be possible. Using the locale-specific char‐
779       acter in bc's input would introduce ambiguities into the language; con‐
780       sider the following example in a locale with a <comma> as the  decimal-
781       point character:
782
783           define f(a,b) {
784               ...
785           }
786           ...
787
788           f(1,2,3)
789
790       Because  of  such ambiguities, the <period> character is used in input.
791       Having input follow different conventions from output would be  confus‐
792       ing  in  either pipeline usage or interactive usage, so the <period> is
793       also used in output.
794

EXAMPLES

796       In the shell, the following assigns an approximation of the  first  ten
797       digits of 'π' to the variable x:
798
799           x=$(printf "%s\n" 'scale = 10; 104348/33215' | bc)
800
801       The  following  bc program prints the same approximation of 'π', with a
802       label, to standard output:
803
804           scale = 10
805           "pi equals "
806           104348 / 33215
807
808       The following defines a function to compute an approximate value of the
809       exponential function (note that such a function is predefined if the −l
810       option is specified):
811
812           scale = 20
813           define e(x){
814               auto a, b, c, i, s
815               a = 1
816               b = 1
817               s = 1
818               for (i = 1; 1 == 1; i++){
819                   a = a*x
820                   b = b*i
821                   c = a/b
822                   if (c == 0) {
823                        return(s)
824                   }
825                   s = s+c
826               }
827           }
828
829       The following prints approximate values of the exponential function  of
830       the first ten integers:
831
832           for (i = 1; i <= 10; ++i) {
833               e(i)
834           }
835

RATIONALE

837       The bc utility is implemented historically as a front-end processor for
838       dc; dc was not selected to be  part  of  this  volume  of  POSIX.1‐2008
839       because bc was thought to have a more intuitive programmatic interface.
840       Current implementations that implement bc using dc are expected  to  be
841       compliant.
842
843       The exit status for error conditions has been left unspecified for sev‐
844       eral reasons:
845
846        *  The bc utility is used in both interactive and non-interactive sit‐
847           uations.  Different exit codes may be appropriate for the two uses.
848
849        *  It is unclear when a non-zero exit should be given; divide-by-zero,
850           undefined functions, and syntax errors are all possibilities.
851
852        *  It is not clear what utility the exit status has.
853
854        *  In the 4.3 BSD, System V, and  Ninth  Edition  implementations,  bc
855           works  in conjunction with dc.  The dc utility is the parent, bc is
856           the child. This was done to cleanly terminate bc if dc aborted.
857
858       The decision to have bc exit upon encountering  an  inaccessible  input
859       file is based on the belief that bc file1 file2 is used most often when
860       at least  file1  contains  data/function  declarations/initializations.
861       Having bc continue with prerequisite files missing is probably not use‐
862       ful. There is no implication in the CONSEQUENCES OF ERRORS section that
863       bc  must  check  all  its files for accessibility before opening any of
864       them.
865
866       There was considerable debate on the appropriateness  of  the  language
867       accepted  by bc.  Several reviewers preferred to see either a pure sub‐
868       set of the C language or some changes to make the language more compat‐
869       ible with C.  While the bc language has some obvious similarities to C,
870       it has never claimed to be compatible with any version of C. An  inter‐
871       preter  for  a  subset  of C might be a very worthwhile utility, and it
872       could potentially make bc obsolete. However, no such utility  is  known
873       in  historical practice, and it was not within the scope of this volume
874       of POSIX.1‐2008 to define such a language and utility. If and when they
875       are  defined, it may be appropriate to include them in a future version
876       of this standard. This left the following alternatives:
877
878        1. Exclude any calculator language from this volume of POSIX.1‐2008.
879
880           The consensus of the standard developers was that a simple program‐
881           matic  calculator language is very useful for both applications and
882           interactive users. The only arguments for excluding any  calculator
883           were  that  it would become obsolete if and when a C-compatible one
884           emerged, or that the absence would  encourage  the  development  of
885           such  a  C-compatible  one.  These  arguments  did not sufficiently
886           address the needs of current application developers.
887
888        2. Standardize the historical dc, possibly with minor modifications.
889
890           The consensus of the standard developers was that dc is a fundamen‐
891           tally  less usable language and that that would be far too severe a
892           penalty for avoiding the issue of being similar to but incompatible
893           with C.
894
895        3. Standardize the historical bc, possibly with minor modifications.
896
897           This was the approach taken. Most of the proponents of changing the
898           language would not have been satisfied until most  or  all  of  the
899           incompatibilities  with  C were resolved. Since most of the changes
900           considered most desirable would break historical  applications  and
901           require  significant  modification  to  historical implementations,
902           almost no modifications were made. The one significant modification
903           that  was  made was the replacement of the historical bc assignment
904           operators "=+", and so on, with the more modern "+=",  and  so  on.
905           The  older  versions  are  considered  to  be  fundamentally flawed
906           because of the lexical ambiguity in uses like a=−1.
907
908           In order to permit implementations to deal with  backwards-compati‐
909           bility  as  they  see  fit, the behavior of this one ambiguous con‐
910           struct was made undefined. (At  least  three  implementations  have
911           been  known to support this change already, so the degree of change
912           involved should not be great.)
913
914       The '%' operator is the mathematical remainder operator when  scale  is
915       zero.  The  behavior of this operator for other values of scale is from
916       historical implementations of bc, and has been maintained for the  sake
917       of historical applications despite its non-intuitive nature.
918
919       Historical  implementations permit setting ibase and obase to a broader
920       range of values. This includes values less than 2, which were not  seen
921       as  sufficiently  useful  to  standardize. These implementations do not
922       interpret input properly for values of ibase that are greater than  16.
923       This  is because numeric constants are recognized syntactically, rather
924       than lexically, as described in this volume of POSIX.1‐2008.  They  are
925       built  from  lexical  tokens  of single hexadecimal digits and <period>
926       characters. Since <blank> characters between tokens are not visible  at
927       the  syntactic  level,  it is not possible to recognize the multi-digit
928       ``digits'' used in the higher bases properly. The ability to  recognize
929       input  in these bases was not considered useful enough to require modi‐
930       fying these implementations.  Note that the recognition of numeric con‐
931       stants at the syntactic level is not a problem with conformance to this
932       volume of POSIX.1‐2008, as it does not impact the behavior of  conform‐
933       ing  applications (and correct bc programs). Historical implementations
934       also accept input with all of the digits '0''9' and 'A''F' regardless
935       of the value of ibase; since digits with value greater than or equal to
936       ibase are not really appropriate, the  behavior  when  they  appear  is
937       undefined, except for the common case of:
938
939           ibase=8;
940               /* Process in octal base. */
941           ...
942           ibase=A
943               /* Restore decimal base. */
944
945       In  some historical implementations, if the expression to be written is
946       an uninitialized array element, a leading <space>  and/or  up  to  four
947       leading  0  characters  may  be  output before the character zero. This
948       behavior is considered a bug; it is unlikely that  any  currently  con‐
949       forming application relies on:
950
951           echo 'b[3]' | bc
952
953       returning 00000 rather than 0.
954
955       Exact  calculation  of  the number of fractional digits to output for a
956       given value in a base other than 10 can be  computationally  expensive.
957       Historical implementations use a faster approximation, and this is per‐
958       mitted. Note that the requirements apply only to values of  obase  that
959       this  volume  of  POSIX.1‐2008  requires implementations to support (in
960       particular, not to 1, 0, or negative bases, if an  implementation  sup‐
961       ports them as an extension).
962
963       Historical  implementations  of bc did not allow array parameters to be
964       passed as the last parameter to a  function.  New  implementations  are
965       encouraged to remove this restriction even though it is not required by
966       the grammar.
967

FUTURE DIRECTIONS

969       None.
970

SEE ALSO

972       Section 1.3, Grammar Conventions, awk
973
974       The Base Definitions volume of  POSIX.1‐2008,  Chapter  8,  Environment
975       Variables, Section 12.2, Utility Syntax Guidelines
976
978       Portions  of  this text are reprinted and reproduced in electronic form
979       from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology
980       --  Portable  Operating  System  Interface (POSIX), The Open Group Base
981       Specifications Issue 7, Copyright (C) 2013 by the Institute of Electri‐
982       cal  and  Electronics  Engineers,  Inc  and  The  Open Group.  (This is
983       POSIX.1-2008 with the 2013 Technical Corrigendum  1  applied.)  In  the
984       event of any discrepancy between this version and the original IEEE and
985       The Open Group Standard, the original IEEE and The Open Group  Standard
986       is  the  referee document. The original Standard can be obtained online
987       at http://www.unix.org/online.html .
988
989       Any typographical or formatting errors that appear  in  this  page  are
990       most likely to have been introduced during the conversion of the source
991       files to man page format. To report such errors,  see  https://www.ker
992       nel.org/doc/man-pages/reporting_bugs.html .
993
994
995
996IEEE/The Open Group                  2013                               BC(1P)
Impressum