DC(1)
๐
dc(1) โ arbitrary-precision decimal reverse-Polish notation calculator ๐
โจ NAME โจ
bestie, meet dc: the arbitrary-precision decimal reverse-Polish notation calculator. she's giving calculator, but make it stack-based and extra ๐
โจ
๐ SYNOPSIS ๐
okay so the signature vibe is literally this, no cap:
dc [-cChiPRvVx] [--version] [--help] [--digit-clamp] [--no-digit-clamp]
[--interactive] [--no-prompt] [--no-read-prompt] [--extended-register]
[-e expr] [--expression=expr...] [-f file...] [--file=file...]
[file...] [-I ibase] [--ibase=ibase] [-O obase] [--obase=obase] [-S
scale] [--scale=scale] [-E seed] [--seed=seed]
๐ DESCRIPTION ๐
dc(1) is an arbitrary-precision calculator. it uses a stack โ that's reverse Polish notation, iykyk โ to store numbers and results of computations. arithmetic operations pop arguments off of the stack and push the results. iconic behavior, honestly ๐ซถ
if no files are given on the command-line, then dc(1) reads from stdin (see the STDIN section). otherwise, those files are processed, and dc(1) will then exit.
if a user wants to set up a standard environment, they can use DC_ENV_ARGS (see the ENVIRONMENT VARIABLES section). for example, if a user wants the scale always set to 10, they can set DC_ENV_ARGS to -e 10k, and this dc(1) will always start with a scale of 10. slay ๐
๐ OPTIONS ๐
the following are the options that dc(1) accepts. menu time, bestie:
-C,--no-digit-clampโ disables clamping of digits greater than or equal to the currentibasewhen parsing numbers.
this means that the value added to a number from a digit is always that digitโs value multiplied by the value of ibase raised to the power of the digitโs position, which starts from 0 at the least significant digit.
if this and/or the -c or --digit-clamp options are given multiple times, the last one given is used.
this option overrides the DC_DIGIT_CLAMP environment variable (see the ENVIRONMENT VARIABLES section) and the default, which can be queried with the -h or --help options.
this is a non-portable extension.
-c,--digit-clampโ enables clamping of digits greater than or equal to the currentibasewhen parsing numbers.
this means that a digit thatโs greater than or equal to the ibase contributes the value of ibase minus 1 all multiplied by the value of ibase raised to the power of the digitโs position, which starts from 0 at the least significant digit. so yeah, digits get clamped, periodt.
if this and/or the -C or --no-digit-clamp options are given multiple times, the last one given is used.
this option overrides the DC_DIGIT_CLAMP environment variable (see the ENVIRONMENT VARIABLES section) and the default, which can be queried with the -h or --help options.
this is a non-portable extension.
-Eseed,--seed=seedโ sets the builtin variableseedto the value seed assuming that seed is in base10. it is a fatal error if seed is not a valid number ๐ญ
if multiple instances of this option are given, the last is used.
this is a non-portable extension.
-eexpr,--expression=exprโ evaluates expr. if multiple expressions are given, they are evaluated in order. if files are given as well (see below), the expressions and files are evaluated in the order given. this means that if a file is given before an expression, the file is read in and evaluated first.
if this option is given on the command-line (i.e., not in DC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after processing all expressions and files, dc(1) will exit, unless - (stdin) was given as an argument at least once to -f or --file, whether on the command-line or in DC_ENV_ARGS. however, if any other -e, --expression, -f, or --file arguments are given after -f- or equivalent is given, dc(1) will give a fatal error and exit ๐
this is a non-portable extension.
-ffile,--file=fileโ reads in file and evaluates it, line by line, as though it were read through stdin. if expressions are also given (see above), the expressions are evaluated in the order given.
if this option is given on the command-line (i.e., not in DC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after processing all expressions and files, dc(1) will exit, unless - (stdin) was given as an argument at least once to -f or --file. however, if any other -e, --expression, -f, or --file arguments are given after -f- or equivalent is given, dc(1) will give a fatal error and exit.
this is a non-portable extension.
-h,--helpโ prints a usage message and exits. short, sweet, helpful ๐ธ-Iibase,--ibase=ibaseโ sets the builtin variableibaseto the value ibase assuming that ibase is in base10. it is a fatal error if ibase is not a valid number ๐ญ
if multiple instances of this option are given, the last is used.
this is a non-portable extension.
-i,--interactiveโ forces interactive mode. (see the INTERACTIVE MODE section.) โจ
this is a non-portable extension.
-L,--no-line-lengthโ disables line length checking and prints numbers without backslashes and newlines. in other words, this option setsBC_LINE_LENGTHto0(see the ENVIRONMENT VARIABLES section).
this is a non-portable extension.
-Oobase,--obase=obaseโ sets the builtin variableobaseto the value obase assuming that obase is in base10. it is a fatal error if obase is not a valid number ๐ญ
if multiple instances of this option are given, the last is used.
this is a non-portable extension.
-P,--no-promptโ disables the prompt in TTY mode. (the prompt is only enabled in TTY mode. see the TTY MODE section.) this is mostly for those users that do not want a prompt or are not used to having them indc(1). most of those users would want to put this option inDC_ENV_ARGS.
these options override the DC_PROMPT and DC_TTY_MODE environment variables (see the ENVIRONMENT VARIABLES section).
this is a non-portable extension.
-R,--no-read-promptโ disables the read prompt in TTY mode. (the read prompt is only enabled in TTY mode. see the TTY MODE section.) this is mostly for those users that do not want a read prompt or are not used to having them indc(1). most of those users would want to put this option inBC_ENV_ARGS(see the ENVIRONMENT VARIABLES section). this option is also useful in hash bang lines ofdc(1)scripts that prompt for user input.
this option does not disable the regular prompt because the read prompt is only used when the ? command is used.
these options do override the DC_PROMPT and DC_TTY_MODE environment variables (see the ENVIRONMENT VARIABLES section), but only for the read prompt.
this is a non-portable extension.
-Sscale,--scale=scaleโ sets the builtin variablescaleto the value scale assuming that scale is in base10. it is a fatal error if scale is not a valid number ๐ญ
if multiple instances of this option are given, the last is used.
this is a non-portable extension.
-v,-V,--versionโ print the version information (copyright header) and exits.-x,--extended-registerโ enables extended register mode. see the Extended Register Mode subsection of the REGISTERS section for more information.
this is a non-portable extension.
-z,--leading-zeroesโ makesdc(1)print all numbers greater than-1and less than1, and not equal to0, with a leading zero.
this is a non-portable extension.
all long options are non-portable extensions. periodt ๐
๐ฆ STDIN ๐ฆ
if no files are given on the command-line and no files or expressions are given by the -f, --file, -e, or --expression options, then dc(1) reads from stdin.
however, there is a caveat to this.
first, stdin is evaluated a line at a time. the only exception to this is if a string has been finished, but not ended. this means that, except for escaped brackets, all brackets must be balanced before dc(1) parses and executes ๐ง
๐ธ STDOUT ๐ธ
any non-error output is written to stdout. in addition, if history (see the HISTORY section) and the prompt (see the TTY MODE section) are enabled, both are output to stdout.
Note: unlike otherdc(1)implementations, thisdc(1)will issue a fatal error (see the EXIT STATUS section) if it cannot write to stdout, so if stdout is closed, as indc >&-, it will quit with an error. this is done so thatdc(1)can report problems when stdout is redirected to a file.
if there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect stdout to /dev/null.
๐ STDERR ๐
any error output is written to stderr.
Note: unlike otherdc(1)implementations, thisdc(1)will issue a fatal error (see the EXIT STATUS section) if it cannot write to stderr, so if stderr is closed, as indc 2>&-, it will quit with an error. this is done so thatdc(1)can exit with an error code when stderr is redirected to a file.
if there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect stderr to /dev/null.
โจ SYNTAX โจ
Okay so every single item in the input source code is either a number (peep the NUMBERS section) or a command (peep COMMANDS), and each one gets processed and executed in order. Input is processed immediately when entered โ no waiting around, bestie. ๐
ibase is a register (see REGISTERS) that decides how to interpret constant numbers. Itโs the โinputโ base, aka the number base used for interpreting input numbers. ibase starts at 10. The max allowable value for ibase is 16. The min allowable value for ibase is 2. The max allowable value for ibase can be queried in dc(1) programs with the T command. ๐
obase is a register (see REGISTERS) that decides how to output results. Itโs the โoutputโ base, aka the number base used for outputting numbers. obase starts at 10. The max allowable value for obase is DC_BASE_MAX and can be queried with the U command. The min allowable value for obase is 0. If obase is 0, values are output in scientific notation, and if obase is 1, values are output in engineering notation. Otherwise, values are output in the specified base. ๐
Outputting in scientific and engineering notations are non-portable extensions.
The scale of an expression is the number of digits in the result of the expression right of the decimal point, and scale is a register (see REGISTERS) that sets the precision of any operations (with exceptions). scale starts at 0. scale cannot be negative. The max allowable value for scale can be queried in dc(1) programs with the V command. โญ
seed is a register containing the current seed for the pseudo-random number generator. If the current value of seed is queried and stored, then if it is assigned to seed later, the pseudo-random number generator is guaranteed to produce the same sequence of pseudo-random numbers that were generated after the value of seed was first queried. ๐ฆ
Multiple values assigned to seed can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to seed, it is not guaranteed that querying seed immediately after will return the same value. In addition, the value of seed will change after any call to the ' command or the " command that does not receive a value of 0 or 1. The maximum integer returned by the ' command can be queried with the W command. ๐
Note: the values returned by the pseudo-random number generator with the'and"commands are guaranteed to NOT be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they are guaranteed to be reproducible with identical seed values. This means that the pseudo-random values fromdc(1)should only be used where a reproducible stream of pseudo-random numbers is ESSENTIAL. In any other case, use a non-seeded pseudo-random number generator. ๐จ
The pseudo-random number generator, seed, and all associated operations are non-portable extensions.
๐ฌ Comments ๐ฌ
Comments go from # until, and not including, the next newline. This is a non-portable extension. ๐
๐ข NUMBERS ๐ข
Numbers are strings made up of digits, uppercase letters up to F, and at most 1 period for a radix. Numbers can have up to DC_NUM_MAX digits. Uppercase letters are equal to 9 plus their position in the alphabet (i.e., A equals 10, or 9+1). ๐
If a digit or letter makes no sense with the current value of ibase (i.e., they are greater than or equal to the current value of ibase), then the behavior depends on the existence of the -c/--digit-clamp or -C/--no-digit-clamp options (see OPTIONS), the existence and setting of the DC_DIGIT_CLAMP environment variable (see ENVIRONMENT VARIABLES), or the default, which can be queried with the -h/--help option. ๐ง
If clamping is off, then digits or letters that are greater than or equal to the current value of ibase are not changed. Instead, their given value is multiplied by the appropriate power of ibase and added into the number. This means that, with an ibase of 3, the number AB is equal to 3^1*A+3^0*B, which is 3 times 10 plus 11, or 41. โจ
If clamping is on, then digits or letters that are greater than or equal to the current value of ibase are set to the value of the highest valid digit in ibase before being multiplied by the appropriate power of ibase and added into the number. This means that, with an ibase of 3, the number AB is equal to 3^1*2+3^0*2, which is 3 times 2 plus 2, or 8. ๐ฅ
There is one exception to clamping: single-character numbers (i.e., A alone). Such numbers are never clamped and always take the value they would have in the highest possible ibase. This means that A alone always equals decimal 10 and Z alone always equals decimal 35. This behavior is mandated by the standard for bc(1) (see STANDARDS) and is meant to provide an easy way to set the current ibase (with the i command) regardless of the current value of ibase. ๐
If clamping is on, and the clamped value of a character is needed, use a leading zero, i.e., for A, use 0A. ๐
In addition, dc(1) accepts numbers in scientific notation. These have the form <number>e<integer>. The exponent (the portion after the e) must be an integer. An example is 1.89237e9, which is equal to 1892370000. Negative exponents are also allowed, so 4.2890e_3 is equal to 0.0042890. ๐ธ
WARNING: Both the number and the exponent in scientific notation are interpreted according to the currentibase, but the number is still multiplied by10^exponentregardless of the currentibase. For example, ifibaseis16anddc(1)is given the number stringFFeA, the resulting decimal number will be2550000000000, and ifdc(1)is given the number string10e_4, the resulting decimal number will be0.0016. ๐ญ
Accepting input as scientific notation is a non-portable extension.
๐ฎ COMMANDS ๐ฎ
The valid commands are listed below. ๐
๐จ๏ธ Printing ๐จ๏ธ
These commands are used for printing.
Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning 0 to obase using 0o, and engineering notation is activated by assigning 1 to obase using 1o. To deactivate them, just assign a different value to obase. ๐ฆ
Printing numbers in scientific notation and/or engineering notation is a non-portable extension.
pโ Prints the value on top of the stack, whether number or string, and prints a newline after. This does not alter the stack. ๐nโ Prints the value on top of the stack, whether number or string, and pops it off of the stack. โจPโ Pops a value off the stack. If the value is a number, it is truncated and the absolute value of the result is printed as thoughobaseis256and each digit is interpreted as an 8-bit ASCII character, making it a byte stream. If the value is a string, it is printed without a trailing newline. This is a non-portable extension. ๐ฅfโ Prints the entire contents of the stack, in order from newest to oldest, without altering anything. Users should use this command when they get lost. ๐ซถ
โ Arithmetic โ
These are the commands used for arithmetic.
+โ The top two values are popped off the stack, added, and the result is pushed onto the stack. The scale of the result is equal to the max scale of both operands. ๐-โ The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The scale of the result is equal to the max scale of both operands. ๐*โ The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. Ifais the scale of the first expression andbis the scale of the second expression, the scale of the result is equal tomin(a+b,max(scale,a,b))wheremin()andmax()return the obvious values. ๐/โ The top two values are popped off the stack, divided, and the result is pushed onto the stack. The scale of the result is equal toscale. The first value popped off of the stack must be non-zero. โญ%โ The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. Remaindering is equivalent to 1) Computinga/bto currentscale, and 2) Using the result of step 1 to calculatea-(a/b)*bto scalemax(scale+scale(b),scale(a)). The first value popped off of the stack must be non-zero. ๐~โ The top two values are popped off the stack, divided and remaindered, and the results (divided first, remainder second) are pushed onto the stack. This is equivalent tox y / x y %except thatxandyare only evaluated once. The first value popped off of the stack must be non-zero. This is a non-portable extension. ๐ฆ^โ The top two values are popped off the stack, the second is raised to the power of the first, and the result is pushed onto the stack. The scale of the result is equal toscale. The first value popped off of the stack must be an integer, and if that value is negative, the second value popped off of the stack must be non-zero. ๐ฅvโ The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The scale of the result is equal toscale. The value popped off of the stack must be non-negative. ๐ธ_โ If this command immediately precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. Otherwise, the top value on the stack is popped and copied, and the copy is negated and pushed onto the stack. This behavior without a number is a non-portable extension. ๐bโ The top value is popped off the stack, and if it is zero, it is pushed back onto the stack. Otherwise, its absolute value is pushed onto the stack. This is a non-portable extension. ๐|โ The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. The first value popped is used as the reduction modulus and must be an integer and non-zero. The second value popped is used as the exponent and must be an integer and non-negative. The third value popped is the base and must be an integer. This is a non-portable extension. ๐ง$โ The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. This is a non-portable extension. ๐@โ The top two values are popped off the stack, and the precision of the second is set to the value of the first, whether by truncation or extension. โจ
โฆand yeah, carrying straight on from that last one: the first value popped off of the stack must be an integer and non-negative. No exceptions, bestie. ๐
Hโ pops the top two values, and the second one gets shifted left (which means the radix shifts right) to the value of the first. The first value popped has to be an integer and non-negative. โจ non-portable extension โจhโ pops the top two values, and the second one gets shifted right (radix shifts left) to the value of the first. Again: first value popped = integer, non-negative. โจ non-portable extension โจGโ pops the top two, compares them, pushes a1if they're equal and a0if they're not. โจ non-portable extension โจNโ pops the top value, and if it's a0, pushes a1; otherwise pushes a0. (Yes, it's a hater like that. ๐) โจ non-portable extension โจ(โ pops the top two, compares them, pushes1if the first is less than the second, otherwise0. โจ non-portable extension โจ{โ pops the top two, compares them, pushes1if the first is less than or equal to the second, otherwise0. โจ non-portable extension โจ)โ pops the top two, compares them, pushes1if the first is greater than the second, otherwise0. โจ non-portable extension โจ}โ pops the top two, compares them, pushes1if the first is greater than or equal to the second, otherwise0. โจ non-portable extension โจMโ pops the top two values. If they're both non-zero, a1gets pushed onto the stack. If either one of them is zero, or both are, then a0gets pushed. This is like the&&operator inbc(1), and heads up: it is not a short-circuit operator. โจ non-portable extension โจmโ pops the top two values. If at least one of them is non-zero, a1gets pushed. If both of them are zero, then a0gets pushed. This is like the||operator inbc(1), and also not a short-circuit operator. โจ non-portable extension โจ
๐ฒ Pseudo-Random Number Generator
dc(1) has a built-in pseudo-random number generator, and these commands are how you query it. (Peep the Parameters section for more info about the seed value that controls it. ๐ฑ)
Big ol' caveat, no cap: the pseudo-random number generator is guaranteed to NOT be cryptographically secure. Do not use this for your crypto, bestie, I'm begging. ๐ญ
โโ generates an integer between0andDC_RAND_MAX, inclusive (see the LIMITS section). The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. โจ non-portable extension โจโโ pops a value off the stack, and that value is used as an exclusive upper bound on the integer that'll be generated. If the bound is negative or is a non-integer, an error is raised, anddc(1)resets (see the RESET section) whileseedremains unchanged. If the bound is larger thanDC_RAND_MAX, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers ofDC_RAND_MAX+1, and adding them together โ so the size of integer you can generate with this command is literally unbounded. ๐ซถ Using this command will change the value ofseed, unless the operand is0or1โ in that case,0is pushed onto the stack andseedis not changed. And the generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. โจ non-portable extension โจ
๐ฅ Stack Control
These commands do exactly what they say on the tin โ they control the stack.
cโ removes all items from the stack ("clears" it). Fresh start energy. โจdโ copies the item on top of the stack ("duplicates" it) and pushes the copy onto the stack. Iconic, honestly. ๐rโ swaps ("reverses") the two top items on the stack.Rโ pops ("removes") the top value from the stack. Bye bestie ๐จ
๐ Register Control
These commands control registers (see the REGISTERS section).
srโ pops the value off the top of the stack and stores it into registerr.lrโ copies the value in registerrand pushes it onto the stack. This does not alter the contents ofr. Non-destructive queen. ๐Srโ pops the value off the top of the (main) stack and pushes it onto the stack of registerr. The previous value of the register becomes inaccessible. ๐ฌLrโ pops the value off the top of the stack for registerrand pushes it onto the main stack. The previous value in the stack for registerr, if any, is now accessible via thelrcommand. Yay, she's back! ๐
๐๏ธ Parameters
These commands control the values of ibase, obase, scale, and seed. Also go look at the SYNTAX section, iykyk.
iโ pops the value off the top of the stack and uses it to setibase, which must be between2and16, inclusive. If the value on top of the stack has any scale, the scale is ignored.oโ pops the value off the top of the stack and uses it to setobase, which must be between0andDC_BASE_MAX, inclusive (see the LIMITS section and the NUMBERS section). If the value on top of the stack has any scale, the scale is ignored.kโ pops the value off the top of the stack and uses it to setscale, which must be non-negative. If the value on top of the stack has any scale, the scale is ignored.jโ pops the value off the top of the stack and uses it to setseed. The meaning ofseedis dependent on the current pseudo-random number generator, but it's guaranteed to not change except for new major versions. The scale and sign of the value may be significant. ๐ซก
If a previously used seed value is used again, the pseudo-random number generator is guaranteed to produce the same sequence of pseudo-random numbers as it did when the seed value was previously used โ so it's a little time machine. ๐ฐ๏ธ
The exact value assigned to seed is not guaranteed to be returned if the J command is used. However, if seed does return a different value, both values, when assigned to seed, are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to seed will not produce unique sequences of pseudo-random numbers. ๐
There is no limit to the length (number of significant decimal digits) or scale of the value that can be assigned to seed.
โจ non-portable extension โจ
Iโ pushes the current value ofibaseonto the main stack.Oโ pushes the current value ofobaseonto the main stack.Kโ pushes the current value ofscaleonto the main stack.Jโ pushes the current value ofseedonto the main stack. โจ non-portable extension โจTโ pushes the maximum allowable value ofibaseonto the main stack. โจ non-portable extension โจUโ pushes the maximum allowable value ofobaseonto the main stack. โจ non-portable extension โจVโ pushes the maximum allowable value ofscaleonto the main stack. โจ non-portable extension โจWโ pushes the maximum (inclusive) integer that can be generated with theโpseudo-random number generator command. โจ non-portable extension โจ
๐งต Strings
The following commands control strings.
dc(1) can work with both numbers and strings, and registers (see the REGISTERS section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number โ she's not confused, she's just versatile. ๐
While arithmetic operations have to have numbers and will print an error if given a string, other commands accept strings.
Strings can also be executed as macros. For example, if the string [1pR] is executed as a macro, then the code 1pR is executed, meaning that the 1 will be printed with a newline after and then popped from the stack. Slay. โจ
[characters]โ makes a string containing characters and pushes it onto the stack. If there are brackets ([and]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\) character. And if there's a backslash character in the string, the character after it (even another backslash) is put into the string verbatim, but the (first) backslash is not. ๐ชaโ the value on top of the stack is popped. If it's a number, it's truncated and its absolute value is taken. The result mod256is calculated. If that result is0, push an empty string; otherwise, push a one-character string where the character is the result of the mod interpreted as an ASCII character. If it's a string, then a new string is made: if the original string is empty, the new string is empty; if it's not, then the first character of the original string is used to create the new string as a one-character string. The new string is then pushed onto the stack. โจ non-portable extension โจxโ pops a value off the top of the stack. If it's a number, it's pushed right back onto the stack. If it's a string, it's executed as a macro. This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. ๐ฆ>rโ pops two values off the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of registerrare executed. For example,0 1>awill execute the contents of registera, and1 0>awill not. If either or both of the values are not numbers,dc(1)will raise an error and reset (see the RESET section). ๐ญ>resโ like the above, but will execute registersif the comparison fails. If either or both of the values are not numbers,dc(1)will raise an error and reset (see the RESET section). โจ non-portable extension โจ!>rโ pops two values off the stack; both gotta be numbers, and it compares them. If the first value is not greater than the second (so, less than or equal), the contents of register r get executed. ๐
If either or both of the values are not numbers, dc(1) will raise an error and reset (peep the RESET section).
!>resโ same energy as the one above, except it executes register s if the comparison fails. ๐ฆ
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
This is a non-portable extension.
<rโ pops two values off the stack that must be numbers, then compares them. If the first value is less than the second, the contents of register r get executed.
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
<resโ like the above, but it'll execute register s if the comparison fails. ๐ธ
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
This is a non-portable extension.
!<rโ pops two values off the stack that must be numbers and compares them. If the first value is not less than the second (so, greater than or equal), then the contents of register r get executed.
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
!<resโ like the above, but it'll execute register s if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
This is a non-portable extension.
=rโ pops two values off the stack that must be numbers and compares them. If the first value is equal to the second, the contents of register r get executed. โจ
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
=resโ like the above, but it'll execute register s if the comparison fails.
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
This is a non-portable extension.
!=rโ pops two values off the stack that must be numbers and compares them. If the first value is not equal to the second, the contents of register r get executed.
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
!=resโ like the above, but it'll execute register s if the comparison fails. ๐
If either or both of the values are not numbers, dc(1) will raise an error and reset (see RESET).
This is a non-portable extension.
?โ reads a line from the stdin and executes it. This exists so macros can request input from users. ๐ซถqโ during execution of a macro, this exits the execution of that macro and the execution of the macro that executed it. If there are no macros, or only one macro executing,dc(1)exits.Qโ pops a value from the stack, which must be non-negative, and uses it as the number of macro executions to pop off the execution stack. If the number of levels to pop is greater than the number of executing macros,dc(1)exits.,โ pushes the depth of the execution stack onto the stack. The execution stack is the stack of string executions. The number pushed onto the stack is exactly as many as is needed to makedc(1)exit with theQcommand โ so the sequence,Qwill makedc(1)exit. ๐
This is a non-portable extension.
โจ Status โจ
These commands query status of the stack or its top value. iykyk ๐
Zโ pops a value off the stack.
If it's a number, it calculates the number of significant decimal digits it has and pushes the result. It will push 1 if the argument is 0 with no decimal places.
If it's a string, it pushes the number of characters the string has.
Xโ pops a value off the stack.
If it's a number, it pushes the scale of the value onto the stack.
If it's a string, it pushes 0.
uโ pops one value off the stack. If the value is a number, this pushes1onto the stack. Otherwise (if it's a string), it pushes0.
This is a non-portable extension.
tโ pops one value off the stack. If the value is a string, this pushes1onto the stack. Otherwise (if it's a number), it pushes0. ๐ฅ
This is a non-portable extension.
zโ pushes the current depth of the stack (before execution of this command) onto the stack.yrโ pushes the current stack depth of register r onto the main stack. ๐
Because each register has a depth of 1 (with the value 0 in the top item) when dc(1) starts, dc(1) requires that each register's stack must always have at least one item; dc(1) will give an error and reset otherwise (see RESET). This means that this command will never push 0.
This is a non-portable extension.
๐ฆ Arrays ๐ฆ
These commands manipulate arrays. ๐
:rโ pops the top two values off the stack. The second value gets stored in the array r (see REGISTERS), indexed by the first value.;rโ pops the value on top of the stack and uses it as an index into the array r. The selected value is then pushed onto the stack.Yrโ pushes the length of the array r onto the stack. ๐
This is a non-portable extension.
๐ Global Settings ๐
These commands retrieve global settings. They're the only commands that require multiple specific characters, and every single one of them begins with the letter g. Only the characters listed below are allowed after the character g; any other character produces a parse error (see the ERRORS section). ๐
glโ pushes the line length set byDC_LINE_LENGTH(see the ENVIRONMENT VARIABLES section) onto the stack.gxโ pushes1onto the stack if extended register mode is on,0otherwise. See the Extended Register Mode subsection of the REGISTERS section for more info.gzโ pushes0onto the stack if the leading zero setting has not been enabled with the-zor--leading-zeroesoptions (see OPTIONS), non-zero otherwise.
๐ REGISTERS ๐
Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers, bestie โ separate vibes, separate stacks. โจ)
Each register is also its own stack, so the current register value is the top of the stack for that register. All registers, when first referenced, have one value (0) in their stack, and it is a runtime error to attempt to pop that item off of the register stack. ๐
In non-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exceptions are: a newline (\n) and a left bracket ([) โ it is a parse error for a newline or a left bracket to be used as a register name.
๐ธ Extended Register Mode ๐ธ
Unlike most other dc(1) implementations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. main character energy fr ๐
If extended register mode is enabled (-x or --extended-register command-line arguments are given), then normal single character registers are used unless the character immediately following a command that needs a register name is a space (according to isspace()) and not a newline (\n).
In that case, the register name is found according to the regex [a-z][a-z0-9_]* (like bc(1) identifiers), and it is a parse error if the next non-space characters do not match that regex.
๐ RESET ๐
When dc(1) encounters an error or a signal that it has a non-default handler for, it resets. This means that several things happen.
First, any macros that are executing are stopped and popped off the execution stack. The behavior is not unlike that of exceptions in programming languages. Then the execution point is set so that any code waiting to execute (after all macros returned) is skipped.
However โ and this is the important bit โ the stack of values is not cleared; in interactive mode, users can inspect the stack and manipulate it. ๐
So, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it's interactive mode, and the error was not a fatal error (see the EXIT STATUS section), it asks for more input; otherwise, it exits with the appropriate return code.
ngl, this is the closest dc(1) gets to a "we're so back / it's so over" arc. ๐โจ
๐ฅ PERFORMANCE ๐ฅ
Most dc(1) implementations use char types to calculate the value of 1 decimal digit at a time, but that can be slow. This dc(1) does something different.
It uses large integers to calculate more than 1 decimal digit at a time. If built in an environment where DC_LONG_BIT (see the LIMITS section) is 64, then each integer has 9 decimal digits. If built in an environment where DC_LONG_BIT is 32 then each integer has 4 decimal digits. This value (the number of decimal digits per large integer) is called DC_BASE_DIGS. โญ
In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of DC_LONG_BIT, but is always at least twice as large as the integer type used to store digits. ate and left no crumbs ๐
๐ LIMITS ๐
ok so these are, like, the actual hard ceilings on dc(1) โ the absolute maximums, bestie:
DC_LONG_BITโ the number of bits in thelongtype in whatever environmentdc(1)got built in. this is the thing that decides how many decimal digits can fit in a single large integer (peep the PERFORMANCE section for the tea on that).DC_BASE_DIGSโ how many decimal digits go in each large integer (again, PERFORMANCE section). it depends onDC_LONG_BIT.DC_BASE_POWโ the biggest decimal number each large integer can hold (seeDC_BASE_DIGS) plus 1. yep, it depends onDC_BASE_DIGS.DC_OVERFLOW_MAXโ the biggest number the overflow type can hold (PERFORMANCE section, go look). depends onDC_LONG_BIT.DC_BASE_MAXโ the maximum output base. it's set atDC_BASE_POW.DC_DIM_MAXโ the maximum size of arrays. set atSIZE_MAX-1.DC_SCALE_MAXโ the maximum scale. set atDC_OVERFLOW_MAX-1.DC_STRING_MAXโ the maximum length of strings. set atDC_OVERFLOW_MAX-1.DC_NAME_MAXโ the maximum length of identifiers. set atDC_OVERFLOW_MAX-1.DC_NUM_MAXโ the maximum length of a number, measured in decimal digits, and yes that includes the digits after the decimal point. set atDC_OVERFLOW_MAX-1.DC_RAND_MAXโ the maximum integer (inclusive) that the'command returns, ifdc(1). set at2^DC_LONG_BIT-1.- Exponent โ the maximum allowable exponent, positive or negative. set at
DC_OVERFLOW_MAX. - Number of vars โ the maximum number of vars/arrays. set at
SIZE_MAX-1.
so here's the vibe check on all of these: they're basically meant to be non-existent ๐ like, they're so big (at least on 64-bit machines) that there should not be any point where they become a problem. fr fr, you'd run out of memory before you ever hit these limits. iconic tbh.
๐ธ ENVIRONMENT VARIABLES ๐ธ
as non-portable extensions, dc(1) recognizes these environment variables:
DC_ENV_ARGSโ another way to hand command-line arguments todc(1), and they should be in the same format as all your other command-line arguments. these always get processed first, so any files you give inDC_ENV_ARGSget processed before the arguments and files you give on the command-line. it's giving "let the user set up 'standard' options and files that are used at every invocation" energy. the most useful thing for those files to contain would be useful functions that the user might want every timedc(1)runs. another use would be to use the-eoption to setscaleto a value other than0.
ok important caveat, the code that parses DC_ENV_ARGS will correctly handle quoted arguments, but it does not understand escape sequences. example time:
/home/gavin/some dc file.dc
that one gets parsed correctly โจ but this one:
/home/gavin/some "dc" file.dc
will include the backslashes. yeah. ๐
the quote parsing handles either kind of quotes, ' or ". so if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, like this:
some `dc' file.dc
and vice versa if you've got a file with double quotes. however โ handling a file with both kinds of quotes in DC_ENV_ARGS is not supported, because the parsing would get way too complicated. those files are still supported on the command-line though, where the parsing is done by the shell. ๐ซถ
DC_LINE_LENGTHโ if this environment variable exists and contains an integer that's greater than1and less thanUINT16_MAX(2^16-1),dc(1)will output lines to that length, including the backslash newline combo. the default line length is70.
the special value of 0 will disable line length checking entirely, and print numbers without regard to line length and without backslashes and newlines. no cap. ๐
DC_SIGINT_RESETโ ifdc(1)is not in interactive mode (see the INTERACTIVE MODE section), then this environment variable has no effect, becausedc(1)exits onSIGINTwhen it's not in interactive mode.
but! when dc(1) is in interactive mode, then if this environment variable exists and contains an integer, a non-zero value makes dc(1) reset on SIGINT rather than exit, and zero makes dc(1) exit. if this environment variable exists and is not an integer, then dc(1) will exit on SIGINT.
this environment variable overrides the default, which you can query with the -h or --help options.
DC_TTY_MODEโ if TTY mode is not available (see the TTY MODE section), then this environment variable has no effect.
but when TTY mode is available, then if this environment variable exists and contains an integer, a non-zero value makes dc(1) use TTY mode, and zero makes dc(1) not use TTY mode.
this environment variable overrides the default, which can be queried with the -h or --help options.
DC_PROMPTโ if TTY mode is not available (see the TTY MODE section), then this environment variable has no effect.
but when TTY mode is available, then if this environment variable exists and contains an integer, a non-zero value makes dc(1) use a prompt, and zero or a non-integer makes dc(1) not use a prompt. if this environment variable does not exist and DC_TTY_MODE does, then the value of the DC_TTY_MODE environment variable is used.
this environment variable and the DC_TTY_MODE environment variable override the default, which can be queried with the -h or --help options.
DC_EXPR_EXITโ if any expressions or expression files are given on the command-line with-e,--expression,-f, or--file, then if this environment variable exists and contains an integer, a non-zero value makesdc(1)exit after executing the expressions and expression files, and a zero value makesdc(1)not exit.
this environment variable overrides the default, which can be queried with the -h or --help options.
DC_DIGIT_CLAMPโ when parsing numbers, and if this environment variable exists and contains an integer, a non-zero value makesdc(1)clamp digits that are greater than or equal to the currentibaseso that all such digits are considered equal toibaseminus1. a zero value disables that clamping, so those digits are always equal to their value, which gets multiplied by the power of theibase.
this never applies to single-digit numbers, as per the bc(1) standard (see the STANDARDS section).
this environment variable overrides the default, which can be queried with the -h or --help options.
๐ EXIT STATUS ๐
dc(1) returns these exit statuses, bestie, memorize them:
0โ no error. we love a clean run. โจ1โ a math error occurred. this follows the standard practice of using1for expected errors, since math errors will happen in the process of normal execution.
math errors include divide by 0, taking the square root of a negative number, using a negative number as a bound for the pseudo-random number generator, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, overflow when calculating the size of a number, and attempting to use a non-integer where an integer is required.
converting to a hardware integer happens for the second operand of the power (^), places (@), left shift (H), and right shift (h) operators.
2โ a parse error occurred.
parse errors include unexpected EOF, using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid.
3โ a runtime error occurred.
runtime errors include assigning an invalid number to any global (ibase, obase, or scale), giving a bad expression to a read() call, calling read() inside of a read() call, type errors (including attempting to execute a number), and attempting an operation when the stack has too few elements.
4โ a fatal error occurred. ๐ญ
fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (dc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options.
ok so exit status4is special โ when a fatal error occurs,dc(1)always exits and returns4, no matter what modedc(1)is in. no exceptions, periodt.
the other statuses will only be returned when dc(1) is not in interactive mode (see the INTERACTIVE MODE section), since dc(1) resets its state (see the RESET section) and accepts more input when one of those errors occurs in interactive mode. this is also the case when interactive mode is forced by the -i flag or --interactive option.
these exit statuses allow dc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the -i flag or --interactive option. ๐
๐ฆ INTERACTIVE MODE ๐ฆ
like bc(1), dc(1) has an interactive mode and a non-interactive mode. interactive mode gets turned on automatically when both stdin and stdout are hooked to a terminal, but the -i flag and --interactive option can turn it on in other situations too.
in interactive mode, dc(1) attempts to recover from errors (see the RESET section), and in normal execution, flushes stdout as soon as execution is done for the current input. dc(1) may also reset on SIGINT instead of exit, depending on the contents of, or default for, the DC_SIGINT_RESET environment variable (see the ENVIRONMENT VARIABLES section). ๐
๐ธ TTY MODE ๐ธ
Okay so bestie, here's the tea on TTY mode โ โ if stdin, stdout, and stderr are all three connected to a TTY, then "TTY mode" is considered to be available, and thus dc(1) can turn on TTY mode โ subject to some settings, obviously. It's giving "you can come to the party but only if you meet the dress code" ๐
If there is the environment variable DC_TTY_MODE in the environment (peep the ENVIRONMENT VARIABLES section), then if that environment variable contains a non-zero integer, dc(1) will turn on TTY mode when stdin, stdout, and stderr are all connected to a TTY. But if the DC_TTY_MODE environment variable exists but is not a non-zero integer, then dc(1) will not turn TTY mode on. No TTY for you, bestie ๐ซ
If the environment variable DC_TTY_MODE does not exist, the default setting is used. And you can literally just ask what that default is with the -h or --help options ๐ซถ
Bestie it is SO important to know this: TTY mode is different from interactive mode ๐ค Because interactive mode is required in thebc(1)specification (see the STANDARDS section), and interactive mode requires onlystdinandstdoutto be connected to a terminal. TTY mode is the pickier one, periodt ๐
๐ Command-Line History ๐
Command-line history is only enabled if TTY mode is, i.e., that stdin, stdout, and stderr are connected to a TTY and the DC_TTY_MODE environment variable (see the ENVIRONMENT VARIABLES section) and its default do not disable TTY mode. See the COMMAND LINE HISTORY section for more information ๐
โจ Prompt โจ
If TTY mode is available, then a prompt can be enabled. And like TTY mode itself, it can be turned on or off with an environment variable: DC_PROMPT (see the ENVIRONMENT VARIABLES section) ๐
If the environment variable DC_PROMPT exists and is a non-zero integer, then the prompt is turned on when stdin, stdout, and stderr are connected to a TTY and the -P and --no-prompt options were not used. The read prompt will be turned on under the same conditions, except that the -R and --no-read-prompt options must also not be used ๐
However, if DC_PROMPT does not exist, the prompt can be enabled or disabled with the DC_TTY_MODE environment variable, the -P and --no-prompt options, and the -R and --no-read-prompt options. See the ENVIRONMENT VARIABLES and OPTIONS sections for more details ๐
๐ SIGNAL HANDLING ๐
Sending a SIGINT will cause dc(1) to do one of two things. Choose-your-own-adventure vibes fr fr ๐ฆ
Option one: if dc(1) is not in interactive mode (see the INTERACTIVE MODE section), or the DC_SIGINT_RESET environment variable (see the ENVIRONMENT VARIABLES section), or its default, is either not an integer or it is zero, dc(1) will exit. Bye bestie ๐๐ญ
Option two: however, if dc(1) is in interactive mode, and the DC_SIGINT_RESET or its default is an integer and non-zero, then dc(1) will stop executing the current input and reset (see the RESET section) upon receiving a SIGINT. Slay, it lives to compute another day โจ
Now, note that "current input" can mean one of two things ๐ If dc(1) is processing input from stdin in interactive mode, it will ask for more input. If dc(1) is processing input from a file in interactive mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from stdin if no other file exists.
This means that if aSIGINTis sent todc(1)as it is executing a file, it can seem as thoughdc(1)did not respond to the signal โ since it will immediately start executing the next file ๐ญ No cap, that's just how it is. This is by design; most files that users execute when interacting withdc(1)have function definitions, which are quick to parse. If a file takes a long time to execute, there may be a bug in that file ๐ The rest of the files could still be executed without problem, allowing the user to continue. The show must go on ๐
SIGTERM and SIGQUIT cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is SIGHUP; in that case, and only when dc(1) is in TTY mode (see the TTY MODE section), a SIGHUP will cause dc(1) to clean up and exit. Weirdly specific but okay, we respect the lore ๐
โญ COMMAND LINE HISTORY โญ
dc(1) supports interactive command-line editing โจ (yes, you can hit the up arrow, king)
If dc(1) can be in TTY mode (see the TTY MODE section), history can be enabled. This means that command-line history can only be enabled when stdin, stdout, and stderr are all connected to a TTY ๐ฅ
Like TTY mode itself, it can be turned on or off with the environment variable DC_TTY_MODE (see the ENVIRONMENT VARIABLES section) ๐
๐ Note: tabs are converted to 8 spaces. That's it, that's the note. Eight whole spaces. Iconic.
๐ฆ SEE ALSO ๐ฆ
That's the whole list, bestie. Just the one. The sibling ๐ซถ
๐ STANDARDS ๐
The dc(1) utility operators and some behavior are compliant with the operators in the IEEE Std 1003.1-2017 ("POSIX.1-2017") bc(1) specification at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html ๐โจ
๐ BUGS ๐
None are known. (Not me being flawless ๐
โจ) Report bugs at https://github.com/gavinhoward/bc ๐
๐ AUTHOR ๐
Gavin D. Howard gavin@gavinhoward.com and contributors. Shoutout to the contributors, y'all are the main characters fr fr ๐ซถ๐
And that's the whole page, bestie โ we ate and left no crumbs ๐ This was written by Gavin D. Howard, dated August 2024, and it's the DC(1) page. Go forth and compute, ily ๐๐งโโ๏ธ
๐ฆ where this page comes from
- alpine 3.24: howard-bc-doc 7.1.0-r1 ยท BSD-2-Clause
- ๐ the page's license: BSD-2-Clause
- Copyright (c) 2018-2025 Gavin D. Howard and contributors
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms