xref: /freebsd/contrib/bc/manuals/dc/HN.1.md (revision cab6a39d7b343596a5823e65c0f7b426551ec22d)
1<!---
2
3SPDX-License-Identifier: BSD-2-Clause
4
5Copyright (c) 2018-2021 Gavin D. Howard and contributors.
6
7Redistribution and use in source and binary forms, with or without
8modification, are permitted provided that the following conditions are met:
9
10* Redistributions of source code must retain the above copyright notice, this
11  list of conditions and the following disclaimer.
12
13* Redistributions in binary form must reproduce the above copyright notice,
14  this list of conditions and the following disclaimer in the documentation
15  and/or other materials provided with the distribution.
16
17THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
21LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27POSSIBILITY OF SUCH DAMAGE.
28
29-->
30
31# Name
32
33dc - arbitrary-precision decimal reverse-Polish notation calculator
34
35# SYNOPSIS
36
37**dc** [**-hiPRvVx**] [**-\-version**] [**-\-help**] [**-\-interactive**] [**-\-no-prompt**] [**-\-no-read-prompt**] [**-\-extended-register**] [**-e** *expr*] [**-\-expression**=*expr*...] [**-f** *file*...] [**-\-file**=*file*...] [*file*...]
38
39# DESCRIPTION
40
41dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish
42notation) to store numbers and results of computations. Arithmetic operations
43pop arguments off of the stack and push the results.
44
45If no files are given on the command-line, then dc(1) reads from **stdin** (see
46the **STDIN** section). Otherwise, those files are processed, and dc(1) will
47then exit.
48
49If a user wants to set up a standard environment, they can use **DC_ENV_ARGS**
50(see the **ENVIRONMENT VARIABLES** section). For example, if a user wants the
51**scale** always set to **10**, they can set **DC_ENV_ARGS** to **-e 10k**, and
52this dc(1) will always start with a **scale** of **10**.
53
54# OPTIONS
55
56The following are the options that dc(1) accepts.
57
58**-h**, **-\-help**
59
60:   Prints a usage message and quits.
61
62**-v**, **-V**, **-\-version**
63
64:   Print the version information (copyright header) and exit.
65
66**-i**, **-\-interactive**
67
68:   Forces interactive mode. (See the **INTERACTIVE MODE** section.)
69
70    This is a **non-portable extension**.
71
72**-P**, **-\-no-prompt**
73
74:   Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode.
75    See the **TTY MODE** section.) This is mostly for those users that do not
76    want a prompt or are not used to having them in dc(1). Most of those users
77    would want to put this option in **DC_ENV_ARGS**.
78
79    These options override the **DC_PROMPT** and **DC_TTY_MODE** environment
80    variables (see the **ENVIRONMENT VARIABLES** section).
81
82    This is a **non-portable extension**.
83
84**-R**, **-\-no-read-prompt**
85
86:   Disables the read prompt in TTY mode. (The read prompt is only enabled in
87    TTY mode. See the **TTY MODE** section.) This is mostly for those users that
88    do not want a read prompt or are not used to having them in dc(1). Most of
89    those users would want to put this option in **BC_ENV_ARGS** (see the
90    **ENVIRONMENT VARIABLES** section). This option is also useful in hash bang
91    lines of dc(1) scripts that prompt for user input.
92
93    This option does not disable the regular prompt because the read prompt is
94    only used when the **?** command is used.
95
96    These options *do* override the **DC_PROMPT** and **DC_TTY_MODE**
97    environment variables (see the **ENVIRONMENT VARIABLES** section), but only
98    for the read prompt.
99
100    This is a **non-portable extension**.
101
102**-x** **-\-extended-register**
103
104:   Enables extended register mode. See the *Extended Register Mode* subsection
105    of the **REGISTERS** section for more information.
106
107    This is a **non-portable extension**.
108
109**-e** *expr*, **-\-expression**=*expr*
110
111:   Evaluates *expr*. If multiple expressions are given, they are evaluated in
112    order. If files are given as well (see below), the expressions and files are
113    evaluated in the order given. This means that if a file is given before an
114    expression, the file is read in and evaluated first.
115
116    If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
117    see the **ENVIRONMENT VARIABLES** section), then after processing all
118    expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
119    as an argument at least once to **-f** or **-\-file**, whether on the
120    command-line or in **DC_ENV_ARGS**. However, if any other **-e**,
121    **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-**
122    or equivalent is given, dc(1) will give a fatal error and exit.
123
124    This is a **non-portable extension**.
125
126**-f** *file*, **-\-file**=*file*
127
128:   Reads in *file* and evaluates it, line by line, as though it were read
129    through **stdin**. If expressions are also given (see above), the
130    expressions are evaluated in the order given.
131
132    If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**,
133    see the **ENVIRONMENT VARIABLES** section), then after processing all
134    expressions and files, dc(1) will exit, unless **-** (**stdin**) was given
135    as an argument at least once to **-f** or **-\-file**. However, if any other
136    **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after
137    **-f-** or equivalent is given, dc(1) will give a fatal error and exit.
138
139    This is a **non-portable extension**.
140
141All long options are **non-portable extensions**.
142
143# STDIN
144
145If no files are given on the command-line and no files or expressions are given
146by the **-f**, **-\-file**, **-e**, or **-\-expression** options, then dc(1)
147read from **stdin**.
148
149However, there is a caveat to this.
150
151First, **stdin** is evaluated a line at a time. The only exception to this is if
152a string has been finished, but not ended. This means that, except for escaped
153brackets, all brackets must be balanced before dc(1) parses and executes.
154
155# STDOUT
156
157Any non-error output is written to **stdout**. In addition, if history (see the
158**HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled,
159both are output to **stdout**.
160
161**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
162error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if
163**stdout** is closed, as in **dc <file> >&-**, it will quit with an error. This
164is done so that dc(1) can report problems when **stdout** is redirected to a
165file.
166
167If there are scripts that depend on the behavior of other dc(1) implementations,
168it is recommended that those scripts be changed to redirect **stdout** to
169**/dev/null**.
170
171# STDERR
172
173Any error output is written to **stderr**.
174
175**Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal
176error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if
177**stderr** is closed, as in **dc <file> 2>&-**, it will quit with an error. This
178is done so that dc(1) can exit with an error code when **stderr** is redirected
179to a file.
180
181If there are scripts that depend on the behavior of other dc(1) implementations,
182it is recommended that those scripts be changed to redirect **stderr** to
183**/dev/null**.
184
185# SYNTAX
186
187Each item in the input source code, either a number (see the **NUMBERS**
188section) or a command (see the **COMMANDS** section), is processed and executed,
189in order. Input is processed immediately when entered.
190
191**ibase** is a register (see the **REGISTERS** section) that determines how to
192interpret constant numbers. It is the "input" base, or the number base used for
193interpreting input numbers. **ibase** is initially **10**. The max allowable
194value for **ibase** is **16**. The min allowable value for **ibase** is **2**.
195The max allowable value for **ibase** can be queried in dc(1) programs with the
196**T** command.
197
198**obase** is a register (see the **REGISTERS** section) that determines how to
199output results. It is the "output" base, or the number base used for outputting
200numbers. **obase** is initially **10**. The max allowable value for **obase** is
201**DC_BASE_MAX** and can be queried with the **U** command. The min allowable
202value for **obase** is **0**. If **obase** is **0**, values are output in
203scientific notation, and if **obase** is **1**, values are output in engineering
204notation. Otherwise, values are output in the specified base.
205
206Outputting in scientific and engineering notations are **non-portable
207extensions**.
208
209The *scale* of an expression is the number of digits in the result of the
210expression right of the decimal point, and **scale** is a register (see the
211**REGISTERS** section) that sets the precision of any operations (with
212exceptions). **scale** is initially **0**. **scale** cannot be negative. The max
213allowable value for **scale** can be queried in dc(1) programs with the **V**
214command.
215
216**seed** is a register containing the current seed for the pseudo-random number
217generator. If the current value of **seed** is queried and stored, then if it is
218assigned to **seed** later, the pseudo-random number generator is guaranteed to
219produce the same sequence of pseudo-random numbers that were generated after the
220value of **seed** was first queried.
221
222Multiple values assigned to **seed** can produce the same sequence of
223pseudo-random numbers. Likewise, when a value is assigned to **seed**, it is not
224guaranteed that querying **seed** immediately after will return the same value.
225In addition, the value of **seed** will change after any call to the **'**
226command or the **"** command that does not get receive a value of **0** or
227**1**. The maximum integer returned by the **'** command can be queried with the
228**W** command.
229
230**Note**: The values returned by the pseudo-random number generator with the
231**'** and **"** commands are guaranteed to **NOT** be cryptographically secure.
232This is a consequence of using a seeded pseudo-random number generator. However,
233they *are* guaranteed to be reproducible with identical **seed** values. This
234means that the pseudo-random values from dc(1) should only be used where a
235reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case,
236use a non-seeded pseudo-random number generator.
237
238The pseudo-random number generator, **seed**, and all associated operations are
239**non-portable extensions**.
240
241## Comments
242
243Comments go from **#** until, and not including, the next newline. This is a
244**non-portable extension**.
245
246# NUMBERS
247
248Numbers are strings made up of digits, uppercase letters up to **F**, and at
249most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits.
250Uppercase letters are equal to **9** + their position in the alphabet (i.e.,
251**A** equals **10**, or **9+1**). If a digit or letter makes no sense with the
252current value of **ibase**, they are set to the value of the highest valid digit
253in **ibase**.
254
255Single-character numbers (i.e., **A** alone) take the value that they would have
256if they were valid digits, regardless of the value of **ibase**. This means that
257**A** alone always equals decimal **10** and **F** alone always equals decimal
258**15**.
259
260In addition, dc(1) accepts numbers in scientific notation. These have the form
261**\<number\>e\<integer\>**. The exponent (the portion after the **e**) must be
262an integer. An example is **1.89237e9**, which is equal to **1892370000**.
263Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**.
264
265**WARNING**: Both the number and the exponent in scientific notation are
266interpreted according to the current **ibase**, but the number is still
267multiplied by **10\^exponent** regardless of the current **ibase**. For example,
268if **ibase** is **16** and dc(1) is given the number string **FFeA**, the
269resulting decimal number will be **2550000000000**, and if dc(1) is given the
270number string **10e_4**, the resulting decimal number will be **0.0016**.
271
272Accepting input as scientific notation is a **non-portable extension**.
273
274# COMMANDS
275
276The valid commands are listed below.
277
278## Printing
279
280These commands are used for printing.
281
282Note that both scientific notation and engineering notation are available for
283printing numbers. Scientific notation is activated by assigning **0** to
284**obase** using **0o**, and engineering notation is activated by assigning **1**
285to **obase** using **1o**. To deactivate them, just assign a different value to
286**obase**.
287
288Printing numbers in scientific notation and/or engineering notation is a
289**non-portable extension**.
290
291**p**
292
293:   Prints the value on top of the stack, whether number or string, and prints a
294    newline after.
295
296    This does not alter the stack.
297
298**n**
299
300:   Prints the value on top of the stack, whether number or string, and pops it
301    off of the stack.
302
303**P**
304
305:   Pops a value off the stack.
306
307    If the value is a number, it is truncated and the absolute value of the
308    result is printed as though **obase** is **256** and each digit is
309    interpreted as an 8-bit ASCII character, making it a byte stream.
310
311    If the value is a string, it is printed without a trailing newline.
312
313    This is a **non-portable extension**.
314
315**f**
316
317:   Prints the entire contents of the stack, in order from newest to oldest,
318    without altering anything.
319
320    Users should use this command when they get lost.
321
322## Arithmetic
323
324These are the commands used for arithmetic.
325
326**+**
327
328:   The top two values are popped off the stack, added, and the result is pushed
329    onto the stack. The *scale* of the result is equal to the max *scale* of
330    both operands.
331
332**-**
333
334:   The top two values are popped off the stack, subtracted, and the result is
335    pushed onto the stack. The *scale* of the result is equal to the max
336    *scale* of both operands.
337
338**\***
339
340:   The top two values are popped off the stack, multiplied, and the result is
341    pushed onto the stack. If **a** is the *scale* of the first expression and
342    **b** is the *scale* of the second expression, the *scale* of the result
343    is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return
344    the obvious values.
345
346**/**
347
348:   The top two values are popped off the stack, divided, and the result is
349    pushed onto the stack. The *scale* of the result is equal to **scale**.
350
351    The first value popped off of the stack must be non-zero.
352
353**%**
354
355:   The top two values are popped off the stack, remaindered, and the result is
356    pushed onto the stack.
357
358    Remaindering is equivalent to 1) Computing **a/b** to current **scale**, and
359    2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale*
360    **max(scale+scale(b),scale(a))**.
361
362    The first value popped off of the stack must be non-zero.
363
364**~**
365
366:   The top two values are popped off the stack, divided and remaindered, and
367    the results (divided first, remainder second) are pushed onto the stack.
368    This is equivalent to **x y / x y %** except that **x** and **y** are only
369    evaluated once.
370
371    The first value popped off of the stack must be non-zero.
372
373    This is a **non-portable extension**.
374
375**\^**
376
377:   The top two values are popped off the stack, the second is raised to the
378    power of the first, and the result is pushed onto the stack. The *scale* of
379    the result is equal to **scale**.
380
381    The first value popped off of the stack must be an integer, and if that
382    value is negative, the second value popped off of the stack must be
383    non-zero.
384
385**v**
386
387:   The top value is popped off the stack, its square root is computed, and the
388    result is pushed onto the stack. The *scale* of the result is equal to
389    **scale**.
390
391    The value popped off of the stack must be non-negative.
392
393**\_**
394
395:   If this command *immediately* precedes a number (i.e., no spaces or other
396    commands), then that number is input as a negative number.
397
398    Otherwise, the top value on the stack is popped and copied, and the copy is
399    negated and pushed onto the stack. This behavior without a number is a
400    **non-portable extension**.
401
402**b**
403
404:   The top value is popped off the stack, and if it is zero, it is pushed back
405    onto the stack. Otherwise, its absolute value is pushed onto the stack.
406
407    This is a **non-portable extension**.
408
409**|**
410
411:   The top three values are popped off the stack, a modular exponentiation is
412    computed, and the result is pushed onto the stack.
413
414    The first value popped is used as the reduction modulus and must be an
415    integer and non-zero. The second value popped is used as the exponent and
416    must be an integer and non-negative. The third value popped is the base and
417    must be an integer.
418
419    This is a **non-portable extension**.
420
421**\$**
422
423:   The top value is popped off the stack and copied, and the copy is truncated
424    and pushed onto the stack.
425
426    This is a **non-portable extension**.
427
428**\@**
429
430:   The top two values are popped off the stack, and the precision of the second
431    is set to the value of the first, whether by truncation or extension.
432
433    The first value popped off of the stack must be an integer and non-negative.
434
435    This is a **non-portable extension**.
436
437**H**
438
439:   The top two values are popped off the stack, and the second is shifted left
440    (radix shifted right) to the value of the first.
441
442    The first value popped off of the stack must be an integer and non-negative.
443
444    This is a **non-portable extension**.
445
446**h**
447
448:   The top two values are popped off the stack, and the second is shifted right
449    (radix shifted left) to the value of the first.
450
451    The first value popped off of the stack must be an integer and non-negative.
452
453    This is a **non-portable extension**.
454
455**G**
456
457:   The top two values are popped off of the stack, they are compared, and a
458    **1** is pushed if they are equal, or **0** otherwise.
459
460    This is a **non-portable extension**.
461
462**N**
463
464:   The top value is popped off of the stack, and if it a **0**, a **1** is
465    pushed; otherwise, a **0** is pushed.
466
467    This is a **non-portable extension**.
468
469**(**
470
471:   The top two values are popped off of the stack, they are compared, and a
472    **1** is pushed if the first is less than the second, or **0** otherwise.
473
474    This is a **non-portable extension**.
475
476**{**
477
478:   The top two values are popped off of the stack, they are compared, and a
479    **1** is pushed if the first is less than or equal to the second, or **0**
480    otherwise.
481
482    This is a **non-portable extension**.
483
484**)**
485
486:   The top two values are popped off of the stack, they are compared, and a
487    **1** is pushed if the first is greater than the second, or **0** otherwise.
488
489    This is a **non-portable extension**.
490
491**}**
492
493:   The top two values are popped off of the stack, they are compared, and a
494    **1** is pushed if the first is greater than or equal to the second, or
495    **0** otherwise.
496
497    This is a **non-portable extension**.
498
499**M**
500
501:   The top two values are popped off of the stack. If they are both non-zero, a
502    **1** is pushed onto the stack. If either of them is zero, or both of them
503    are, then a **0** is pushed onto the stack.
504
505    This is like the **&&** operator in bc(1), and it is *not* a short-circuit
506    operator.
507
508    This is a **non-portable extension**.
509
510**m**
511
512:   The top two values are popped off of the stack. If at least one of them is
513    non-zero, a **1** is pushed onto the stack. If both of them are zero, then a
514    **0** is pushed onto the stack.
515
516    This is like the **||** operator in bc(1), and it is *not* a short-circuit
517    operator.
518
519    This is a **non-portable extension**.
520
521## Pseudo-Random Number Generator
522
523dc(1) has a built-in pseudo-random number generator. These commands query the
524pseudo-random number generator. (See Parameters for more information about the
525**seed** value that controls the pseudo-random number generator.)
526
527The pseudo-random number generator is guaranteed to **NOT** be
528cryptographically secure.
529
530**'**
531
532:   Generates an integer between 0 and **DC_RAND_MAX**, inclusive (see the
533    **LIMITS** section).
534
535    The generated integer is made as unbiased as possible, subject to the
536    limitations of the pseudo-random number generator.
537
538    This is a **non-portable extension**.
539
540**"**
541
542:   Pops a value off of the stack, which is used as an **exclusive** upper bound
543    on the integer that will be generated. If the bound is negative or is a
544    non-integer, an error is raised, and dc(1) resets (see the **RESET**
545    section) while **seed** remains unchanged. If the bound is larger than
546    **DC_RAND_MAX**, the higher bound is honored by generating several
547    pseudo-random integers, multiplying them by appropriate powers of
548    **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that
549    can be generated with this command is unbounded. Using this command will
550    change the value of **seed**, unless the operand is **0** or **1**. In that
551    case, **0** is pushed onto the stack, and **seed** is *not* changed.
552
553    The generated integer is made as unbiased as possible, subject to the
554    limitations of the pseudo-random number generator.
555
556    This is a **non-portable extension**.
557
558## Stack Control
559
560These commands control the stack.
561
562**c**
563
564:   Removes all items from ("clears") the stack.
565
566**d**
567
568:   Copies the item on top of the stack ("duplicates") and pushes the copy onto
569    the stack.
570
571**r**
572
573:   Swaps ("reverses") the two top items on the stack.
574
575**R**
576
577:   Pops ("removes") the top value from the stack.
578
579## Register Control
580
581These commands control registers (see the **REGISTERS** section).
582
583**s**_r_
584
585:   Pops the value off the top of the stack and stores it into register *r*.
586
587**l**_r_
588
589:   Copies the value in register *r* and pushes it onto the stack. This does not
590    alter the contents of *r*.
591
592**S**_r_
593
594:   Pops the value off the top of the (main) stack and pushes it onto the stack
595    of register *r*. The previous value of the register becomes inaccessible.
596
597**L**_r_
598
599:   Pops the value off the top of the stack for register *r* and push it onto
600    the main stack. The previous value in the stack for register *r*, if any, is
601    now accessible via the **l**_r_ command.
602
603## Parameters
604
605These commands control the values of **ibase**, **obase**, **scale**, and
606**seed**. Also see the **SYNTAX** section.
607
608**i**
609
610:   Pops the value off of the top of the stack and uses it to set **ibase**,
611    which must be between **2** and **16**, inclusive.
612
613    If the value on top of the stack has any *scale*, the *scale* is ignored.
614
615**o**
616
617:   Pops the value off of the top of the stack and uses it to set **obase**,
618    which must be between **0** and **DC_BASE_MAX**, inclusive (see the
619    **LIMITS** section and the **NUMBERS** section).
620
621    If the value on top of the stack has any *scale*, the *scale* is ignored.
622
623**k**
624
625:   Pops the value off of the top of the stack and uses it to set **scale**,
626    which must be non-negative.
627
628    If the value on top of the stack has any *scale*, the *scale* is ignored.
629
630**j**
631
632:   Pops the value off of the top of the stack and uses it to set **seed**. The
633    meaning of **seed** is dependent on the current pseudo-random number
634    generator but is guaranteed to not change except for new major versions.
635
636    The *scale* and sign of the value may be significant.
637
638    If a previously used **seed** value is used again, the pseudo-random number
639    generator is guaranteed to produce the same sequence of pseudo-random
640    numbers as it did when the **seed** value was previously used.
641
642    The exact value assigned to **seed** is not guaranteed to be returned if the
643    **J** command is used. However, if **seed** *does* return a different value,
644    both values, when assigned to **seed**, are guaranteed to produce the same
645    sequence of pseudo-random numbers. This means that certain values assigned
646    to **seed** will not produce unique sequences of pseudo-random numbers.
647
648    There is no limit to the length (number of significant decimal digits) or
649    *scale* of the value that can be assigned to **seed**.
650
651    This is a **non-portable extension**.
652
653**I**
654
655:   Pushes the current value of **ibase** onto the main stack.
656
657**O**
658
659:   Pushes the current value of **obase** onto the main stack.
660
661**K**
662
663:   Pushes the current value of **scale** onto the main stack.
664
665**J**
666
667:   Pushes the current value of **seed** onto the main stack.
668
669    This is a **non-portable extension**.
670
671**T**
672
673:   Pushes the maximum allowable value of **ibase** onto the main stack.
674
675    This is a **non-portable extension**.
676
677**U**
678
679:   Pushes the maximum allowable value of **obase** onto the main stack.
680
681    This is a **non-portable extension**.
682
683**V**
684
685:   Pushes the maximum allowable value of **scale** onto the main stack.
686
687    This is a **non-portable extension**.
688
689**W**
690
691:   Pushes the maximum (inclusive) integer that can be generated with the **'**
692    pseudo-random number generator command.
693
694    This is a **non-portable extension**.
695
696## Strings
697
698The following commands control strings.
699
700dc(1) can work with both numbers and strings, and registers (see the
701**REGISTERS** section) can hold both strings and numbers. dc(1) always knows
702whether the contents of a register are a string or a number.
703
704While arithmetic operations have to have numbers, and will print an error if
705given a string, other commands accept strings.
706
707Strings can also be executed as macros. For example, if the string **[1pR]** is
708executed as a macro, then the code **1pR** is executed, meaning that the **1**
709will be printed with a newline after and then popped from the stack.
710
711**\[**_characters_**\]**
712
713:   Makes a string containing *characters* and pushes it onto the stack.
714
715    If there are brackets (**\[** and **\]**) in the string, then they must be
716    balanced. Unbalanced brackets can be escaped using a backslash (**\\**)
717    character.
718
719    If there is a backslash character in the string, the character after it
720    (even another backslash) is put into the string verbatim, but the (first)
721    backslash is not.
722
723**a**
724
725:   The value on top of the stack is popped.
726
727    If it is a number, it is truncated and its absolute value is taken. The
728    result mod **256** is calculated. If that result is **0**, push an empty
729    string; otherwise, push a one-character string where the character is the
730    result of the mod interpreted as an ASCII character.
731
732    If it is a string, then a new string is made. If the original string is
733    empty, the new string is empty. If it is not, then the first character of
734    the original string is used to create the new string as a one-character
735    string. The new string is then pushed onto the stack.
736
737    This is a **non-portable extension**.
738
739**x**
740
741:   Pops a value off of the top of the stack.
742
743    If it is a number, it is pushed back onto the stack.
744
745    If it is a string, it is executed as a macro.
746
747    This behavior is the norm whenever a macro is executed, whether by this
748    command or by the conditional execution commands below.
749
750**\>**_r_
751
752:   Pops two values off of the stack that must be numbers and compares them. If
753    the first value is greater than the second, then the contents of register
754    *r* are executed.
755
756    For example, **0 1>a** will execute the contents of register **a**, and
757    **1 0>a** will not.
758
759    If either or both of the values are not numbers, dc(1) will raise an error
760    and reset (see the **RESET** section).
761
762**>**_r_**e**_s_
763
764:   Like the above, but will execute register *s* if the comparison fails.
765
766    If either or both of the values are not numbers, dc(1) will raise an error
767    and reset (see the **RESET** section).
768
769    This is a **non-portable extension**.
770
771**!\>**_r_
772
773:   Pops two values off of the stack that must be numbers and compares them. If
774    the first value is not greater than the second (less than or equal to), then
775    the contents of register *r* are executed.
776
777    If either or both of the values are not numbers, dc(1) will raise an error
778    and reset (see the **RESET** section).
779
780**!\>**_r_**e**_s_
781
782:   Like the above, but will execute register *s* if the comparison fails.
783
784    If either or both of the values are not numbers, dc(1) will raise an error
785    and reset (see the **RESET** section).
786
787    This is a **non-portable extension**.
788
789**\<**_r_
790
791:   Pops two values off of the stack that must be numbers and compares them. If
792    the first value is less than the second, then the contents of register *r*
793    are executed.
794
795    If either or both of the values are not numbers, dc(1) will raise an error
796    and reset (see the **RESET** section).
797
798**\<**_r_**e**_s_
799
800:   Like the above, but will execute register *s* if the comparison fails.
801
802    If either or both of the values are not numbers, dc(1) will raise an error
803    and reset (see the **RESET** section).
804
805    This is a **non-portable extension**.
806
807**!\<**_r_
808
809:   Pops two values off of the stack that must be numbers and compares them. If
810    the first value is not less than the second (greater than or equal to), then
811    the contents of register *r* are executed.
812
813    If either or both of the values are not numbers, dc(1) will raise an error
814    and reset (see the **RESET** section).
815
816**!\<**_r_**e**_s_
817
818:   Like the above, but will execute register *s* if the comparison fails.
819
820    If either or both of the values are not numbers, dc(1) will raise an error
821    and reset (see the **RESET** section).
822
823    This is a **non-portable extension**.
824
825**=**_r_
826
827:   Pops two values off of the stack that must be numbers and compares them. If
828    the first value is equal to the second, then the contents of register *r*
829    are executed.
830
831    If either or both of the values are not numbers, dc(1) will raise an error
832    and reset (see the **RESET** section).
833
834**=**_r_**e**_s_
835
836:   Like the above, but will execute register *s* if the comparison fails.
837
838    If either or both of the values are not numbers, dc(1) will raise an error
839    and reset (see the **RESET** section).
840
841    This is a **non-portable extension**.
842
843**!=**_r_
844
845:   Pops two values off of the stack that must be numbers and compares them. If
846    the first value is not equal to the second, then the contents of register
847    *r* are executed.
848
849    If either or both of the values are not numbers, dc(1) will raise an error
850    and reset (see the **RESET** section).
851
852**!=**_r_**e**_s_
853
854:   Like the above, but will execute register *s* if the comparison fails.
855
856    If either or both of the values are not numbers, dc(1) will raise an error
857    and reset (see the **RESET** section).
858
859    This is a **non-portable extension**.
860
861**?**
862
863:   Reads a line from the **stdin** and executes it. This is to allow macros to
864    request input from users.
865
866**q**
867
868:   During execution of a macro, this exits the execution of that macro and the
869    execution of the macro that executed it. If there are no macros, or only one
870    macro executing, dc(1) exits.
871
872**Q**
873
874:   Pops a value from the stack which must be non-negative and is used the
875    number of macro executions to pop off of the execution stack. If the number
876    of levels to pop is greater than the number of executing macros, dc(1)
877    exits.
878
879**,**
880
881:   Pushes the depth of the execution stack onto the stack. The execution stack
882    is the stack of string executions. The number that is pushed onto the stack
883    is exactly as many as is needed to make dc(1) exit with the **Q** command,
884    so the sequence **,Q** will make dc(1) exit.
885
886## Status
887
888These commands query status of the stack or its top value.
889
890**Z**
891
892:   Pops a value off of the stack.
893
894    If it is a number, calculates the number of significant decimal digits it
895    has and pushes the result. It will push **1** if the argument is **0** with
896    no decimal places.
897
898    If it is a string, pushes the number of characters the string has.
899
900**X**
901
902:   Pops a value off of the stack.
903
904    If it is a number, pushes the *scale* of the value onto the stack.
905
906    If it is a string, pushes **0**.
907
908**z**
909
910:   Pushes the current depth of the stack (before execution of this command)
911    onto the stack.
912
913**y**_r_
914
915:   Pushes the current stack depth of the register *r* onto the main stack.
916
917    Because each register has a depth of **1** (with the value **0** in the top
918    item) when dc(1) starts, dc(1) requires that each register's stack must
919    always have at least one item; dc(1) will give an error and reset otherwise
920    (see the **RESET** section). This means that this command will never push
921    **0**.
922
923    This is a **non-portable extension**.
924
925## Arrays
926
927These commands manipulate arrays.
928
929**:**_r_
930
931:   Pops the top two values off of the stack. The second value will be stored in
932    the array *r* (see the **REGISTERS** section), indexed by the first value.
933
934**;**_r_
935
936:   Pops the value on top of the stack and uses it as an index into the array
937    *r*. The selected value is then pushed onto the stack.
938
939**Y**_r_
940
941:   Pushes the length of the array *r* onto the stack.
942
943    This is a **non-portable extension**.
944
945# REGISTERS
946
947Registers are names that can store strings, numbers, and arrays. (Number/string
948registers do not interfere with array registers.)
949
950Each register is also its own stack, so the current register value is the top of
951the stack for the register. All registers, when first referenced, have one value
952(**0**) in their stack, and it is a runtime error to attempt to pop that item
953off of the register stack.
954
955In non-extended register mode, a register name is just the single character that
956follows any command that needs a register name. The only exceptions are: a
957newline (**'\\n'**) and a left bracket (**'['**); it is a parse error for a
958newline or a left bracket to be used as a register name.
959
960## Extended Register Mode
961
962Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited
963amounts of registers, if extended register mode is enabled.
964
965If extended register mode is enabled (**-x** or **-\-extended-register**
966command-line arguments are given), then normal single character registers are
967used *unless* the character immediately following a command that needs a
968register name is a space (according to **isspace()**) and not a newline
969(**'\\n'**).
970
971In that case, the register name is found according to the regex
972**\[a-z\]\[a-z0-9\_\]\*** (like bc(1) identifiers), and it is a parse error if
973the next non-space characters do not match that regex.
974
975# RESET
976
977When dc(1) encounters an error or a signal that it has a non-default handler
978for, it resets. This means that several things happen.
979
980First, any macros that are executing are stopped and popped off the stack.
981The behavior is not unlike that of exceptions in programming languages. Then
982the execution point is set so that any code waiting to execute (after all
983macros returned) is skipped.
984
985Thus, when dc(1) resets, it skips any remaining code waiting to be executed.
986Then, if it is interactive mode, and the error was not a fatal error (see the
987**EXIT STATUS** section), it asks for more input; otherwise, it exits with the
988appropriate return code.
989
990# PERFORMANCE
991
992Most dc(1) implementations use **char** types to calculate the value of **1**
993decimal digit at a time, but that can be slow. This dc(1) does something
994different.
995
996It uses large integers to calculate more than **1** decimal digit at a time. If
997built in a environment where **DC_LONG_BIT** (see the **LIMITS** section) is
998**64**, then each integer has **9** decimal digits. If built in an environment
999where **DC_LONG_BIT** is **32** then each integer has **4** decimal digits. This
1000value (the number of decimal digits per large integer) is called
1001**DC_BASE_DIGS**.
1002
1003In addition, this dc(1) uses an even larger integer for overflow checking. This
1004integer type depends on the value of **DC_LONG_BIT**, but is always at least
1005twice as large as the integer type used to store digits.
1006
1007# LIMITS
1008
1009The following are the limits on dc(1):
1010
1011**DC_LONG_BIT**
1012
1013:   The number of bits in the **long** type in the environment where dc(1) was
1014    built. This determines how many decimal digits can be stored in a single
1015    large integer (see the **PERFORMANCE** section).
1016
1017**DC_BASE_DIGS**
1018
1019:   The number of decimal digits per large integer (see the **PERFORMANCE**
1020    section). Depends on **DC_LONG_BIT**.
1021
1022**DC_BASE_POW**
1023
1024:   The max decimal number that each large integer can store (see
1025    **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**.
1026
1027**DC_OVERFLOW_MAX**
1028
1029:   The max number that the overflow type (see the **PERFORMANCE** section) can
1030    hold. Depends on **DC_LONG_BIT**.
1031
1032**DC_BASE_MAX**
1033
1034:   The maximum output base. Set at **DC_BASE_POW**.
1035
1036**DC_DIM_MAX**
1037
1038:   The maximum size of arrays. Set at **SIZE_MAX-1**.
1039
1040**DC_SCALE_MAX**
1041
1042:   The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**.
1043
1044**DC_STRING_MAX**
1045
1046:   The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**.
1047
1048**DC_NAME_MAX**
1049
1050:   The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**.
1051
1052**DC_NUM_MAX**
1053
1054:   The maximum length of a number (in decimal digits), which includes digits
1055    after the decimal point. Set at **DC_OVERFLOW_MAX-1**.
1056
1057**DC_RAND_MAX**
1058
1059:   The maximum integer (inclusive) returned by the **'** command, if dc(1). Set
1060    at **2\^DC_LONG_BIT-1**.
1061
1062Exponent
1063
1064:   The maximum allowable exponent (positive or negative). Set at
1065    **DC_OVERFLOW_MAX**.
1066
1067Number of vars
1068
1069:   The maximum number of vars/arrays. Set at **SIZE_MAX-1**.
1070
1071These limits are meant to be effectively non-existent; the limits are so large
1072(at least on 64-bit machines) that there should not be any point at which they
1073become a problem. In fact, memory should be exhausted before these limits should
1074be hit.
1075
1076# ENVIRONMENT VARIABLES
1077
1078dc(1) recognizes the following environment variables:
1079
1080**DC_ENV_ARGS**
1081
1082:   This is another way to give command-line arguments to dc(1). They should be
1083    in the same format as all other command-line arguments. These are always
1084    processed first, so any files given in **DC_ENV_ARGS** will be processed
1085    before arguments and files given on the command-line. This gives the user
1086    the ability to set up "standard" options and files to be used at every
1087    invocation. The most useful thing for such files to contain would be useful
1088    functions that the user might want every time dc(1) runs. Another use would
1089    be to use the **-e** option to set **scale** to a value other than **0**.
1090
1091    The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments,
1092    but it does not understand escape sequences. For example, the string
1093    **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string
1094    **"/home/gavin/some \"dc\" file.dc"** will include the backslashes.
1095
1096    The quote parsing will handle either kind of quotes, **'** or **"**. Thus,
1097    if you have a file with any number of single quotes in the name, you can use
1098    double quotes as the outside quotes, as in **"some 'dc' file.dc"**, and vice
1099    versa if you have a file with double quotes. However, handling a file with
1100    both kinds of quotes in **DC_ENV_ARGS** is not supported due to the
1101    complexity of the parsing, though such files are still supported on the
1102    command-line where the parsing is done by the shell.
1103
1104**DC_LINE_LENGTH**
1105
1106:   If this environment variable exists and contains an integer that is greater
1107    than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output
1108    lines to that length, including the backslash newline combo. The default
1109    line length is **70**.
1110
1111**DC_SIGINT_RESET**
1112
1113:   If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section),
1114    then this environment variable has no effect because dc(1) exits on
1115    **SIGINT** when not in interactive mode.
1116
1117    However, when dc(1) is in interactive mode, then if this environment
1118    variable exists and contains an integer, a non-zero value makes dc(1) reset
1119    on **SIGINT**, rather than exit, and zero makes dc(1) exit. If this
1120    environment variable exists and is *not* an integer, then dc(1) will exit on
1121    **SIGINT**.
1122
1123    This environment variable overrides the default, which can be queried with
1124    the **-h** or **-\-help** options.
1125
1126**DC_TTY_MODE**
1127
1128:   If TTY mode is *not* available (see the **TTY MODE** section), then this
1129    environment variable has no effect.
1130
1131    However, when TTY mode is available, then if this environment variable
1132    exists and contains an integer, then a non-zero value makes dc(1) use TTY
1133    mode, and zero makes dc(1) not use TTY mode.
1134
1135    This environment variable overrides the default, which can be queried with
1136    the **-h** or **-\-help** options.
1137
1138**DC_PROMPT**
1139
1140:   If TTY mode is *not* available (see the **TTY MODE** section), then this
1141    environment variable has no effect.
1142
1143    However, when TTY mode is available, then if this environment variable
1144    exists and contains an integer, a non-zero value makes dc(1) use a prompt,
1145    and zero or a non-integer makes dc(1) not use a prompt. If this environment
1146    variable does not exist and **DC_TTY_MODE** does, then the value of the
1147    **DC_TTY_MODE** environment variable is used.
1148
1149    This environment variable and the **DC_TTY_MODE** environment variable
1150    override the default, which can be queried with the **-h** or **-\-help**
1151    options.
1152
1153# EXIT STATUS
1154
1155dc(1) returns the following exit statuses:
1156
1157**0**
1158
1159:   No error.
1160
1161**1**
1162
1163:   A math error occurred. This follows standard practice of using **1** for
1164    expected errors, since math errors will happen in the process of normal
1165    execution.
1166
1167    Math errors include divide by **0**, taking the square root of a negative
1168    number, using a negative number as a bound for the pseudo-random number
1169    generator, attempting to convert a negative number to a hardware integer,
1170    overflow when converting a number to a hardware integer, overflow when
1171    calculating the size of a number, and attempting to use a non-integer where
1172    an integer is required.
1173
1174    Converting to a hardware integer happens for the second operand of the power
1175    (**\^**), places (**\@**), left shift (**H**), and right shift (**h**)
1176    operators.
1177
1178**2**
1179
1180:   A parse error occurred.
1181
1182    Parse errors include unexpected **EOF**, using an invalid character, failing
1183    to find the end of a string or comment, and using a token where it is
1184    invalid.
1185
1186**3**
1187
1188:   A runtime error occurred.
1189
1190    Runtime errors include assigning an invalid number to any global (**ibase**,
1191    **obase**, or **scale**), giving a bad expression to a **read()** call,
1192    calling **read()** inside of a **read()** call, type errors (including
1193    attempting to execute a number), and attempting an operation when the stack
1194    has too few elements.
1195
1196**4**
1197
1198:   A fatal error occurred.
1199
1200    Fatal errors include memory allocation errors, I/O errors, failing to open
1201    files, attempting to use files that do not have only ASCII characters (dc(1)
1202    only accepts ASCII characters), attempting to open a directory as a file,
1203    and giving invalid command-line options.
1204
1205The exit status **4** is special; when a fatal error occurs, dc(1) always exits
1206and returns **4**, no matter what mode dc(1) is in.
1207
1208The other statuses will only be returned when dc(1) is not in interactive mode
1209(see the **INTERACTIVE MODE** section), since dc(1) resets its state (see the
1210**RESET** section) and accepts more input when one of those errors occurs in
1211interactive mode. This is also the case when interactive mode is forced by the
1212**-i** flag or **-\-interactive** option.
1213
1214These exit statuses allow dc(1) to be used in shell scripting with error
1215checking, and its normal behavior can be forced by using the **-i** flag or
1216**-\-interactive** option.
1217
1218# INTERACTIVE MODE
1219
1220Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
1221Interactive mode is turned on automatically when both **stdin** and **stdout**
1222are hooked to a terminal, but the **-i** flag and **-\-interactive** option can
1223turn it on in other situations.
1224
1225In interactive mode, dc(1) attempts to recover from errors (see the **RESET**
1226section), and in normal execution, flushes **stdout** as soon as execution is
1227done for the current input. dc(1) may also reset on **SIGINT** instead of exit,
1228depending on the contents of, or default for, the **DC_SIGINT_RESET**
1229environment variable (see the **ENVIRONMENT VARIABLES** section).
1230
1231# TTY MODE
1232
1233If **stdin**, **stdout**, and **stderr** are all connected to a TTY, then "TTY
1234mode" is considered to be available, and thus, dc(1) can turn on TTY mode,
1235subject to some settings.
1236
1237If there is the environment variable **DC_TTY_MODE** in the environment (see the
1238**ENVIRONMENT VARIABLES** section), then if that environment variable contains a
1239non-zero integer, dc(1) will turn on TTY mode when **stdin**, **stdout**, and
1240**stderr** are all connected to a TTY. If the **DC_TTY_MODE** environment
1241variable exists but is *not* a non-zero integer, then dc(1) will not turn TTY
1242mode on.
1243
1244If the environment variable **DC_TTY_MODE** does *not* exist, the default
1245setting is used. The default setting can be queried with the **-h** or
1246**-\-help** options.
1247
1248TTY mode is different from interactive mode because interactive mode is required
1249in the [bc(1) specification][1], and interactive mode requires only **stdin**
1250and **stdout** to be connected to a terminal.
1251
1252## Prompt
1253
1254If TTY mode is available, then a prompt can be enabled. Like TTY mode itself, it
1255can be turned on or off with an environment variable: **DC_PROMPT** (see the
1256**ENVIRONMENT VARIABLES** section).
1257
1258If the environment variable **DC_PROMPT** exists and is a non-zero integer, then
1259the prompt is turned on when **stdin**, **stdout**, and **stderr** are connected
1260to a TTY and the **-P** and **-\-no-prompt** options were not used. The read
1261prompt will be turned on under the same conditions, except that the **-R** and
1262**-\-no-read-prompt** options must also not be used.
1263
1264However, if **DC_PROMPT** does not exist, the prompt can be enabled or disabled
1265with the **DC_TTY_MODE** environment variable, the **-P** and **-\-no-prompt**
1266options, and the **-R** and **-\-no-read-prompt** options. See the **ENVIRONMENT
1267VARIABLES** and **OPTIONS** sections for more details.
1268
1269# SIGNAL HANDLING
1270
1271Sending a **SIGINT** will cause dc(1) to do one of two things.
1272
1273If dc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), or
1274the **DC_SIGINT_RESET** environment variable (see the **ENVIRONMENT VARIABLES**
1275section), or its default, is either not an integer or it is zero, dc(1) will
1276exit.
1277
1278However, if dc(1) is in interactive mode, and the **DC_SIGINT_RESET** or its
1279default is an integer and non-zero, then dc(1) will stop executing the current
1280input and reset (see the **RESET** section) upon receiving a **SIGINT**.
1281
1282Note that "current input" can mean one of two things. If dc(1) is processing
1283input from **stdin** in interactive mode, it will ask for more input. If dc(1)
1284is processing input from a file in interactive mode, it will stop processing the
1285file and start processing the next file, if one exists, or ask for input from
1286**stdin** if no other file exists.
1287
1288This means that if a **SIGINT** is sent to dc(1) as it is executing a file, it
1289can seem as though dc(1) did not respond to the signal since it will immediately
1290start executing the next file. This is by design; most files that users execute
1291when interacting with dc(1) have function definitions, which are quick to parse.
1292If a file takes a long time to execute, there may be a bug in that file. The
1293rest of the files could still be executed without problem, allowing the user to
1294continue.
1295
1296**SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the
1297default handler for all other signals.
1298
1299# SEE ALSO
1300
1301bc(1)
1302
1303# STANDARDS
1304
1305The dc(1) utility operators are compliant with the operators in the bc(1)
1306[IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification.
1307
1308# BUGS
1309
1310None are known. Report bugs at https://git.yzena.com/gavin/bc.
1311
1312# AUTHOR
1313
1314Gavin D. Howard <gavin@yzena.com> and contributors.
1315
1316[1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
1317