Index: head/contrib/bc/Makefile.in =================================================================== --- head/contrib/bc/Makefile.in (revision 363809) +++ head/contrib/bc/Makefile.in (revision 363810) @@ -1,364 +1,364 @@ # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2020 Gavin D. Howard and contributors. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # %%WARNING%% # .POSIX: -VERSION = 3.1.3 +VERSION = 3.1.4 SRC = %%SRC%% OBJ = %%OBJ%% GCDA = %%GCDA%% GCNO = %%GCNO%% BC_SRC = %%BC_SRC%% BC_OBJ = %%BC_OBJ%% BC_GCDA = %%BC_GCDA%% BC_GCNO = %%BC_GCNO%% DC_SRC = %%DC_SRC%% DC_OBJ = %%DC_OBJ%% DC_GCDA = %%DC_GCDA%% DC_GCNO = %%DC_GCNO%% HISTORY_SRC = %%HISTORY_SRC%% HISTORY_OBJ = %%HISTORY_OBJ%% HISTORY_GCDA = %%HISTORY_GCDA%% HISTORY_GCNO = %%HISTORY_GCNO%% RAND_SRC = %%RAND_SRC%% RAND_OBJ = %%RAND_OBJ%% RAND_GCDA = %%RAND_GCDA%% RAND_GCNO = %%RAND_GCNO%% BC_ENABLED_NAME = BC_ENABLED BC_ENABLED = %%BC_ENABLED%% DC_ENABLED_NAME = DC_ENABLED DC_ENABLED = %%DC_ENABLED%% GEN_DIR = gen GEN = %%GEN%% GEN_EXEC = $(GEN_DIR)/$(GEN) GEN_C = $(GEN_DIR)/$(GEN).c GEN_EMU = %%GEN_EMU%% BC_LIB = $(GEN_DIR)/lib.bc BC_LIB_C = $(GEN_DIR)/lib.c BC_LIB_O = %%BC_LIB_O%% BC_LIB_GCDA = $(GEN_DIR)/lib.gcda BC_LIB_GCNO = $(GEN_DIR)/lib.gcno BC_LIB2 = $(GEN_DIR)/lib2.bc BC_LIB2_C = $(GEN_DIR)/lib2.c BC_LIB2_O = %%BC_LIB2_O%% BC_LIB2_GCDA = $(GEN_DIR)/lib2.gcda BC_LIB2_GCNO = $(GEN_DIR)/lib2.gcno BC_HELP = $(GEN_DIR)/bc_help.txt BC_HELP_C = $(GEN_DIR)/bc_help.c BC_HELP_O = %%BC_HELP_O%% BC_HELP_GCDA = $(GEN_DIR)/bc_help.gcda BC_HELP_GCNO = $(GEN_DIR)/bc_help.gcno DC_HELP = $(GEN_DIR)/dc_help.txt DC_HELP_C = $(GEN_DIR)/dc_help.c DC_HELP_O = %%DC_HELP_O%% DC_HELP_GCDA = $(GEN_DIR)/dc_help.gcda DC_HELP_GCNO = $(GEN_DIR)/dc_help.gcno BIN = bin LOCALES = locales EXEC_SUFFIX = %%EXECSUFFIX%% EXEC_PREFIX = %%EXECPREFIX%% BC = bc DC = dc BC_EXEC = $(BIN)/$(EXEC_PREFIX)$(BC) DC_EXEC = $(BIN)/$(EXEC_PREFIX)$(DC) MANUALS = manuals BC_MANPAGE_NAME = $(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX).1 BC_MANPAGE = $(MANUALS)/$(BC).1 BC_MD = $(BC_MANPAGE).md DC_MANPAGE_NAME = $(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX).1 DC_MANPAGE = $(MANUALS)/$(DC).1 DC_MD = $(DC_MANPAGE).md MANPAGE_INSTALL_ARGS = -Dm644 %%DESTDIR%% BINDIR = %%BINDIR%% MAN1DIR = %%MAN1DIR%% MAIN_EXEC = $(EXEC_PREFIX)$(%%MAIN_EXEC%%)$(EXEC_SUFFIX) EXEC = $(%%EXEC%%) NLSPATH = %%NLSPATH%% BC_ENABLE_HISTORY = %%HISTORY%% BC_ENABLE_EXTRA_MATH_NAME = BC_ENABLE_EXTRA_MATH BC_ENABLE_EXTRA_MATH = %%EXTRA_MATH%% BC_ENABLE_NLS = %%NLS%% BC_ENABLE_PROMPT = %%PROMPT%% BC_LONG_BIT = %%LONG_BIT%% RM = rm MKDIR = mkdir INSTALL = ./install.sh SAFE_INSTALL = ./safe-install.sh LINK = ./link.sh MANPAGE = ./manpage.sh KARATSUBA = ./karatsuba.py LOCALE_INSTALL = ./locale_install.sh LOCALE_UNINSTALL = ./locale_uninstall.sh VALGRIND_ARGS = --error-exitcode=100 --leak-check=full --show-leak-kinds=all --errors-for-leak-kinds=all BC_NUM_KARATSUBA_LEN = %%KARATSUBA_LEN%% CPPFLAGS1 = -D$(BC_ENABLED_NAME)=$(BC_ENABLED) -D$(DC_ENABLED_NAME)=$(DC_ENABLED) CPPFLAGS2 = $(CPPFLAGS1) -I./include/ -DVERSION=$(VERSION) %%LONG_BIT_DEFINE%% CPPFLAGS3 = $(CPPFLAGS2) -DEXECPREFIX=$(EXEC_PREFIX) -DMAINEXEC=$(MAIN_EXEC) CPPFLAGS4 = $(CPPFLAGS3) -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 CPPFLAGS5 = $(CPPFLAGS4) -DBC_NUM_KARATSUBA_LEN=$(BC_NUM_KARATSUBA_LEN) CPPFLAGS6 = $(CPPFLAGS5) -DBC_ENABLE_NLS=$(BC_ENABLE_NLS) -DBC_ENABLE_PROMPT=$(BC_ENABLE_PROMPT) CPPFLAGS7 = $(CPPFLAGS6) -D$(BC_ENABLE_EXTRA_MATH_NAME)=$(BC_ENABLE_EXTRA_MATH) CPPFLAGS = $(CPPFLAGS7) -DBC_ENABLE_HISTORY=$(BC_ENABLE_HISTORY) CFLAGS = $(CPPFLAGS) %%CPPFLAGS%% %%CFLAGS%% LDFLAGS = %%LDFLAGS%% HOSTCFLAGS = %%HOSTCFLAGS%% CC = %%CC%% HOSTCC = %%HOSTCC%% BC_LIB_C_ARGS = bc_lib bc.h bc_lib_name $(BC_ENABLED_NAME) 1 BC_LIB2_C_ARGS = bc_lib2 bc.h bc_lib2_name "$(BC_ENABLED_NAME) && $(BC_ENABLE_EXTRA_MATH_NAME)" 1 OBJS1 = $(OBJ) $(DC_OBJ) $(BC_OBJ) $(HISTORY_OBJ) $(RAND_OBJ) $(BC_HELP_O) $(DC_HELP_O) OBJS = $(OBJS1) $(BC_LIB_O) $(BC_LIB2_O) $(BC_LIB3_O) OBJ_TARGETS1 = $(DC_HELP_O) $(BC_HELP_O) $(BC_LIB_O) $(BC_LIB2_O) $(BC_LIB3_O) OBJ_TARGETS = $(OBJ_TARGETS1) $(BC_OBJ) $(DC_OBJ) $(HISTORY_OBJ) $(RAND_OBJ) $(OBJ) .c.o: $(CC) $(CFLAGS) -o $@ -c $< all: make_bin $(OBJ_TARGETS) $(CC) $(CFLAGS) $(OBJS) $(LDFLAGS) -o $(EXEC) %%LINK%% $(GEN_EXEC): %%GEN_EXEC_TARGET%% $(BC_LIB_C): $(GEN_EXEC) $(BC_LIB) $(GEN_EMU) $(GEN_EXEC) $(BC_LIB) $(BC_LIB_C) $(BC_LIB_C_ARGS) $(BC_LIB2_C): $(GEN_EXEC) $(BC_LIB2) $(GEN_EMU) $(GEN_EXEC) $(BC_LIB2) $(BC_LIB2_C) $(BC_LIB2_C_ARGS) $(BC_HELP_C): $(GEN_EXEC) $(BC_HELP) $(GEN_EMU) $(GEN_EXEC) $(BC_HELP) $(BC_HELP_C) bc_help bc.h "" $(BC_ENABLED_NAME) $(DC_HELP_C): $(GEN_EXEC) $(DC_HELP) $(GEN_EMU) $(GEN_EXEC) $(DC_HELP) $(DC_HELP_C) dc_help dc.h "" $(DC_ENABLED_NAME) make_bin: $(MKDIR) -p $(BIN) help: @printf 'available targets:\n' @printf '\n' @printf ' all (default) builds %%EXECUTABLES%%\n' @printf ' check alias for `make test`\n' @printf ' clean removes all build files\n' @printf ' clean_config removes all build files as well as the generated Makefile\n' @printf ' clean_tests removes all build files, the generated Makefile,\n' @printf ' and generated tests\n' @printf ' install installs binaries to "%s%s"\n' "$(DESTDIR)" "$(BINDIR)" @printf ' and (if enabled) manpages to "%s%s"\n' "$(DESTDIR)" "$(MAN1DIR)" @printf ' karatsuba runs the karatsuba script (requires Python 3)\n' @printf ' karatsuba_test runs the karatsuba script while running tests\n' @printf ' (requires Python 3)\n' @printf ' uninstall uninstalls binaries from "%s%s"\n' "$(DESTDIR)" "$(BINDIR)" @printf ' and (if enabled) manpages from "%s%s"\n' "$(DESTDIR)" "$(MAN1DIR)" @printf ' test runs the test suite\n' @printf ' test_bc runs the bc test suite, if bc has been built\n' @printf ' test_dc runs the dc test suite, if dc has been built\n' @printf ' time_test runs the test suite, displaying times for some things\n' @printf ' time_test_bc runs the bc test suite, displaying times for some things\n' @printf ' time_test_dc runs the dc test suite, displaying times for some things\n' @printf ' timeconst runs the test on the Linux timeconst.bc script,\n' @printf ' if it exists and bc has been built\n' @printf ' valgrind runs the test suite through valgrind\n' @printf ' valgrind_bc runs the bc test suite, if bc has been built,\n' @printf ' through valgrind\n' @printf ' valgrind_dc runs the dc test suite, if dc has been built,\n' @printf ' through valgrind\n' check: test test: test_bc timeconst test_dc test_bc: %%BC_TEST%% test_dc: %%DC_TEST%% time_test: time_test_bc timeconst time_test_dc time_test_bc: %%BC_TIME_TEST%% time_test_dc: %%DC_TIME_TEST%% timeconst: %%TIMECONST%% valgrind: valgrind_bc valgrind_dc valgrind_bc: %%VG_BC_TEST%% valgrind_dc: %%VG_DC_TEST%% karatsuba: %%KARATSUBA%% karatsuba_test: %%KARATSUBA_TEST%% coverage_output: %%COVERAGE_OUTPUT%% coverage:%%COVERAGE_PREREQS%% version: @printf '%s' "$(VERSION)" libcname: @printf '%s' "$(BC_LIB_C)" extra_math: @printf '%s' "$(BC_ENABLE_EXTRA_MATH)" manpages: $(MANPAGE) bc $(MANPAGE) dc clean_gen: @$(RM) -f $(GEN_EXEC) clean:%%CLEAN_PREREQS%% @printf 'Cleaning files...\n' @$(RM) -f $(OBJ) @$(RM) -f $(BC_OBJ) @$(RM) -f $(DC_OBJ) @$(RM) -f $(HISTORY_OBJ) @$(RM) -f $(RAND_OBJ) @$(RM) -f $(BC_EXEC) @$(RM) -f $(DC_EXEC) @$(RM) -fr $(BIN) @$(RM) -f $(LOCALES)/*.cat @$(RM) -f $(BC_LIB_C) $(BC_LIB_O) @$(RM) -f $(BC_LIB2_C) $(BC_LIB2_O) @$(RM) -f $(BC_HELP_C) $(BC_HELP_O) @$(RM) -f $(DC_HELP_C) $(DC_HELP_O) clean_config: clean @printf 'Cleaning config...\n' @$(RM) -f Makefile @$(RM) -f $(BC_MD) $(DC_MD) @$(RM) -f $(BC_MANPAGE) $(DC_MANPAGE) clean_coverage: @printf 'Cleaning coverage files...\n' @$(RM) -f *.gcov @$(RM) -f *.html @$(RM) -f *.gcda *.gcno @$(RM) -f *.profraw @$(RM) -f $(GCDA) $(GCNO) @$(RM) -f $(BC_GCDA) $(BC_GCNO) @$(RM) -f $(DC_GCDA) $(DC_GCNO) @$(RM) -f $(HISTORY_GCDA) $(HISTORY_GCNO) @$(RM) -f $(RAND_GCDA) $(RAND_GCNO) @$(RM) -f $(BC_LIB_GCDA) $(BC_LIB_GCNO) @$(RM) -f $(BC_LIB2_GCDA) $(BC_LIB2_GCNO) @$(RM) -f $(BC_HELP_GCDA) $(BC_HELP_GCNO) @$(RM) -f $(DC_HELP_GCDA) $(DC_HELP_GCNO) clean_tests: clean clean_config clean_coverage @printf 'Cleaning test files...\n' @$(RM) -f tests/bc/parse.txt tests/bc/parse_results.txt @$(RM) -f tests/bc/print.txt tests/bc/print_results.txt @$(RM) -f tests/bc/bessel.txt tests/bc/bessel_results.txt @$(RM) -f tests/bc/scripts/bessel.txt @$(RM) -f tests/bc/scripts/parse.txt @$(RM) -f tests/bc/scripts/print.txt @$(RM) -f tests/bc/scripts/add.txt @$(RM) -f tests/bc/scripts/divide.txt @$(RM) -f tests/bc/scripts/multiply.txt @$(RM) -f tests/bc/scripts/subtract.txt @$(RM) -f tests/dc/scripts/prime.txt tests/dc/scripts/stream.txt @$(RM) -f .log_*.txt @$(RM) -f .math.txt .results.txt .ops.txt @$(RM) -f .test.txt @$(RM) -f tags .gdbbreakpoints .gdb_history .gdbsetup @$(RM) -f cscope.* @$(RM) -f bc.old install_locales: %%INSTALL_LOCALES%% install_bc_manpage: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BC_MANPAGE) $(DESTDIR)$(MAN1DIR)/$(BC_MANPAGE_NAME) install_dc_manpage: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(DC_MANPAGE) $(DESTDIR)$(MAN1DIR)/$(DC_MANPAGE_NAME) install:%%INSTALL_LOCALES_PREREQS%%%%INSTALL_PREREQS%% $(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)" uninstall_locales: $(LOCALE_UNINSTALL) $(NLSPATH) $(MAIN_EXEC) $(DESTDIR) uninstall_bc_manpage: $(RM) -f $(DESTDIR)$(MAN1DIR)/$(BC_MANPAGE_NAME) uninstall_bc: $(RM) -f $(DESTDIR)$(BINDIR)/$(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX) uninstall_dc_manpage: $(RM) -f $(DESTDIR)$(MAN1DIR)/$(DC_MANPAGE_NAME) uninstall_dc: $(RM) -f $(DESTDIR)$(BINDIR)/$(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX) uninstall:%%UNINSTALL_LOCALES_PREREQS%%%%UNINSTALL_MAN_PREREQS%%%%UNINSTALL_PREREQS%% Index: head/contrib/bc/NEWS.md =================================================================== --- head/contrib/bc/NEWS.md (revision 363809) +++ head/contrib/bc/NEWS.md (revision 363810) @@ -1,896 +1,915 @@ # News +## 3.1.4 + +This is a production release that fixes one bug, changes two behaviors, and +removes one environment variable. + +The bug is like the one in the last release except it applies if files are being +executed. I also made the fix more general. + +The behavior that was changed is that `bc` now exits when given `-e`, `-f`, +`--expression` or `--file`. However, if the last one of those is `-f-` (using +`stdin` as the file), `bc` does not exit. If `-f-` exists and is not the last of +the `-e` and `-f` options (and equivalents), `bc` gives a fatal error and exits. + +Next, I removed the `BC_EXPR_EXIT` and `DC_EXPR_EXIT` environment variables +since their use is not needed with the behavior change. + +Finally, I made it so `bc` does not print the header, though the `-q` and +`--quiet` options were kept for compatibility with GNU `bc`. + ## 3.1.3 This is a production release that fixes one minor bug: if `bc` was invoked like the following, it would error: ``` echo "if (1 < 3) 1" | bc ``` Unless users run into this bug, they do not need to upgrade, but it is suggested that they do. ## 3.1.2 This is a production release that adds a way to install *all* locales. Users do ***NOT*** need to upgrade. For package maintainers wishing to make use of the change, just pass `-l` to `configure.sh`. ## 3.1.1 This is a production release that adds two Spanish locales. Users do ***NOT*** need to upgrade, unless they want those locales. ## 3.1.0 This is a production release that adjusts one behavior, fixes eight bugs, and improves manpages for FreeBSD. Because this release fixes bugs, **users and package maintainers should update to this version as soon as possible**. The behavior that was adjusted was how code from the `-e` and `-f` arguments (and equivalents) were executed. They used to be executed as one big chunk, but in this release, they are now executed line-by-line. The first bug fix in how output to `stdout` was handled in `SIGINT`. If a `SIGINT` came in, the `stdout` buffer was not correctly flushed. In fact, a clean-up function was not getting called. This release fixes that bug. The second bug is in how `dc` handled input from `stdin`. This affected `bc` as well since it was a mishandling of the `stdin` buffer. The third fixed bug was that `bc` and `dc` could `abort()` (in debug mode) when receiving a `SIGTERM`. This one was a race condition with pushing and popping items onto and out of vectors. The fourth bug fixed was that `bc` could leave extra items on the stack and thus, not properly clean up some memory. (The memory would still get `free()`'ed, but it would not be `free()`'ed when it could have been.) The next two bugs were bugs in `bc`'s parser that caused crashes when executing the resulting code. The last two bugs were crashes in `dc` that resulted from mishandling of strings. The manpage improvement was done by switching from [ronn][20] to [Pandoc][21] to generate manpages. Pandoc generates much cleaner manpages and doesn't leave blank lines where they shouldn't be. ## 3.0.3 This is a production release that adds one new feature: specific manpages. Before this release, `bc` and `dc` only used one manpage each that referred to various build options. This release changes it so there is one manpage set per relevant build type. Each manual only has information about its particular build, and `configure.sh` selects the correct set for install. ## 3.0.2 This is a production release that adds `utf8` locale symlinks and removes an unused `auto` variable from the `ceil()` function in the [extended math library][16]. Users do ***NOT*** need to update unless they want the locales. ## 3.0.1 This is a production release with two small changes. Users do ***NOT*** need to upgrade to this release; however, if they haven't upgraded to `3.0.0` yet, it may be worthwhile to upgrade to this release. The first change is fixing a compiler warning on FreeBSD with strict warnings on. The second change is to make the new implementation of `ceil()` in `lib2.bc` much more efficient. ## 3.0.0 *Notes for package maintainers:* *First, the `2.7.0` release series saw a change in the option parsing. This made me change one error message and add a few others. The error message that was changed removed one format specifier. This means that `printf()` will seqfault on old locale files. Unfortunately, `bc` cannot use any locale files except the global ones that are already installed, so it will use the previous ones while running tests during install. **If `bc` segfaults while running arg tests when updating, it is because the global locale files have not been replaced. Make sure to either prevent the test suite from running on update or remove the old locale files before updating.** (Removing the locale files can be done with `make uninstall` or by running the `locale_uninstall.sh` script.) Once this is done, `bc` should install without problems.* *Second, **the option to build without signal support has been removed**. See below for the reasons why.* This is a production release with some small bug fixes, a few improvements, three major bug fixes, and a complete redesign of `bc`'s error and signal handling. **Users and package maintainers should update to this version as soon as possible.** The first major bug fix was in how `bc` executed files. Previously, a whole file was parsed before it was executed, but if a function is defined *after* code, especially if the function definition was actually a redefinition, and the code before the definition referred to the previous function, this `bc` would replace the function before executing any code. The fix was to make sure that all code that existed before a function definition was executed. The second major bug fix was in `bc`'s `lib2.bc`. The `ceil()` function had a bug where a `0` in the decimal place after the truncation position, caused it to output the wrong numbers if there was any non-zero digit after. The third major bug is that when passing parameters to functions, if an expression included an array (not an array element) as a parameter, it was accepted, when it should have been rejected. It is now correctly rejected. Beyond that, this `bc` got several improvements that both sped it up, improved the handling of signals, and improved the error handling. First, the requirements for `bc` were pushed back to POSIX 2008. `bc` uses one function, `strdup()`, which is not in POSIX 2001, and it is in the X/Open System Interfaces group 2001. It is, however, in POSIX 2008, and since POSIX 2008 is old enough to be supported anywhere that I care, that should be the requirement. Second, the BcVm global variable was put into `bss`. This actually slightly reduces the size of the executable from a massive code shrink, and it will stop `bc` from allocating a large set of memory when `bc` starts. Third, the default Karatsuba length was updated from 64 to 32 after making the optimization changes below, since 32 is going to be better than 64 after the changes. Fourth, Spanish translations were added. Fifth, the interpreter received a speedup to make performance on non-math-heavy scripts more competitive with GNU `bc`. While improvements did, in fact, get it much closer (see the [benchmarks][19]), it isn't quite there. There were several things done to speed up the interpreter: First, several small inefficiencies were removed. These inefficiencies included calling the function `bc_vec_pop(v)` twice instead of calling `bc_vec_npop(v, 2)`. They also included an extra function call for checking the size of the stack and checking the size of the stack more than once on several operations. Second, since the current `bc` function is the one that stores constants and strings, the program caches pointers to the current function's vectors of constants and strings to prevent needing to grab the current function in order to grab a constant or a string. Third, `bc` tries to reuse `BcNum`'s (the internal representation of arbitary-precision numbers). If a `BcNum` has the default capacity of `BC_NUM_DEF_SIZE` (32 on 64-bit and 16 on 32-bit) when it is freed, it is added to a list of available `BcNum`'s. And then, when a `BcNum` is allocated with a capacity of `BC_NUM_DEF_SIZE` and any `BcNum`'s exist on the list of reusable ones, one of those ones is grabbed instead. In order to support these changes, the `BC_NUM_DEF_SIZE` was changed. It used to be 16 bytes on all systems, but it was changed to more closely align with the minimum allocation size on Linux, which is either 32 bytes (64-bit musl), 24 bytes (64-bit glibc), 16 bytes (32-bit musl), or 12 bytes (32-bit glibc). Since these are the minimum allocation sizes, these are the sizes that would be allocated anyway, making it worth it to just use the whole space, so the value of `BC_NUM_DEF_SIZE` on 64-bit systems was changed to 32 bytes. On top of that, at least on 64-bit, `BC_NUM_DEF_SIZE` supports numbers with either 72 integer digits or 45 integer digits and 27 fractional digits. This should be more than enough for most cases since `bc`'s default `scale` values are 0 or 20, meaning that, by default, it has at most 20 fractional digits. And 45 integer digits are *a lot*; it's enough to calculate the amount of mass in the Milky Way galaxy in kilograms. Also, 72 digits is enough to calculate the diameter of the universe in Planck lengths. (For 32-bit, these numbers are either 32 integer digits or 12 integer digits and 20 fractional digits. These are also quite big, and going much bigger on a 32-bit system seems a little pointless since 12 digits in just under a trillion and 20 fractional digits is still enough for about any use since `10^-20` light years is just under a millimeter.) All of this together means that for ordinary uses, and even uses in scientific work, the default number size will be all that is needed, which means that nearly all, if not all, numbers will be reused, relieving pressure on the system allocator. I did several experiments to find the changes that had the most impact, especially with regard to reusing `BcNum`'s. One was putting `BcNum`'s into buckets according to their capacity in powers of 2 up to 512. That performed worse than `bc` did in `2.7.2`. Another was putting any `BcNum` on the reuse list that had a capacity of `BC_NUM_DEF_SIZE * 2` and reusing them for `BcNum`'s that requested `BC_NUM_DEF_SIZE`. This did reduce the amount of time spent, but it also spent a lot of time in the system allocator for an unknown reason. (When using `strace`, a bunch more `brk` calls showed up.) Just reusing `BcNum`'s that had exactly `BC_NUM_DEF_SIZE` capacity spent the smallest amount of time in both user and system time. This makes sense, especially with the changes to make `BC_NUM_DEF_SIZE` bigger on 64-bit systems, since the vast majority of numbers will only ever use numbers with a size less than or equal to `BC_NUM_DEF_SIZE`. Last of all, `bc`'s signal handling underwent a complete redesign. (This is the reason that this version is `3.0.0` and not `2.8.0`.) The change was to move from a polling approach to signal handling to an interrupt-based approach. Previously, every single loop condition had a check for signals. I suspect that this could be expensive when in tight loops. Now, the signal handler just uses `longjmp()` (actually `siglongjmp()`) to start an unwinding of the stack until it is stopped or the stack is unwound to `main()`, which just returns. If `bc` is currently executing code that cannot be safely interrupted (according to POSIX), then signals are "locked." The signal handler checks if the lock is taken, and if it is, it just sets the status to indicate that a signal arrived. Later, when the signal lock is released, the status is checked to see if a signal came in. If so, the stack unwinding starts. This design eliminates polling in favor of maintaining a stack of `jmp_buf`'s. This has its own performance implications, but it gives better interaction. And the cost of pushing and popping a `jmp_buf` in a function is paid at most twice. Most functions do not pay that price, and most of the rest only pay it once. (There are only some 3 functions in `bc` that push and pop a `jmp_buf` twice.) As a side effect of this change, I had to eliminate the use of `stdio.h` in `bc` because `stdio` does not play nice with signals and `longjmp()`. I implemented custom I/O buffer code that takes a fraction of the size. This means that static builds will be smaller, but non-static builds will be bigger, though they will have less linking time. This change is also good because my history implementation was already bypassing `stdio` for good reasons, and unifying the architecture was a win. Another reason for this change is that my `bc` should *always* behave correctly in the presence of signals like `SIGINT`, `SIGTERM`, and `SIGQUIT`. With the addition of my own I/O buffering, I needed to also make sure that the buffers were correctly flushed even when such signals happened. For this reason, I **removed the option to build without signal support**. As a nice side effect of this change, the error handling code could be changed to take advantage of the stack unwinding that signals used. This means that signals and error handling use the same code paths, which means that the stack unwinding is well-tested. (Errors are tested heavily in the test suite.) It also means that functions do not need to return a status code that ***every*** caller needs to check. This eliminated over 100 branches that simply checked return codes and then passed that return code up the stack if necessary. The code bloat savings from this is at least 1700 bytes on `x86_64`, *before* taking into account the extra code from removing `stdio.h`. ## 2.7.2 This is a production release with one major bug fix. The `length()` built-in function can take either a number or an array. If it takes an array, it returns the length of the array. Arrays can be passed by reference. The bug is that the `length()` function would not properly dereference arrays that were references. This is a bug that affects all users. **ALL USERS SHOULD UPDATE `bc`**. ## 2.7.1 This is a production release with fixes for new locales and fixes for compiler warnings on FreeBSD. ## 2.7.0 This is a production release with a bug fix for Linux, new translations, and new features. Bug fixes: * Option parsing in `BC_ENV_ARGS` was broken on Linux in 2.6.1 because `glibc`'s `getopt_long()` is broken. To get around that, and to support long options on every platform, an adapted version of [`optparse`][17] was added. Now, `bc` does not even use `getopt()`. * Parsing `BC_ENV_ARGS` with quotes now works. It isn't the smartest, but it does the job if there are spaces in file names. The following new languages are supported: * Dutch * Polish * Russian * Japanes * Simplified Chinese All of these translations were generated using [DeepL][18], so improvements are welcome. There is only one new feature: **`bc` now has a built-in pseudo-random number generator** (PRNG). The PRNG is seeded, making it useful for applications where `/dev/urandom` does not work because output needs to be reproducible. However, it also uses `/dev/urandom` to seed itself by default, so it will start with a good seed by default. It also outputs 32 bits on 32-bit platforms and 64 bits on 64-bit platforms, far better than the 15 bits of C's `rand()` and `bash`'s `$RANDOM`. In addition, the PRNG can take a bound, and when it gets a bound, it automatically adjusts to remove bias. It can also generate numbers of arbitrary size. (As of the time of release, the largest pseudo-random number generated by this `bc` was generated with a bound of `2^(2^20)`.) ***IMPORTANT: read the [`bc` manual][9] and the [`dc` manual][10] to find out exactly what guarantees the PRNG provides. The underlying implementation is not guaranteed to stay the same, but the guarantees that it provides are guaranteed to stay the same regardless of the implementation.*** On top of that, four functions were added to `bc`'s [extended math library][16] to make using the PRNG easier: * `frand(p)`: Generates a number between `[0,1)` to `p` decimal places. * `ifrand(i, p)`: Generates an integer with bound `i` and adds it to `frand(p)`. * `srand(x)`: Randomizes the sign of `x`. In other words, it flips the sign of `x` with probability `0.5`. * `brand()`: Returns a random boolean value (either `0` or `1`). ## 2.6.1 This is a production release with a bug fix for FreeBSD. The bug was that when `bc` was built without long options, it would give a fatal error on every run. This was caused by a mishandling of `optind`. ## 2.6.0 This release is a production release ***with no bugfixes***. If you do not want to upgrade, you don't have to. No source code changed; the only thing that changed was `lib2.bc`. This release adds one function to the [extended math library][16]: `p(x, y)`, which calculates `x` to the power of `y`, whether or not `y` is an integer. (The `^` operator can only accept integer powers.) This release also includes a couple of small tweaks to the [extended math library][16], mostly to fix returning numbers with too high of `scale`. ## 2.5.3 This release is a production release which addresses inconsistencies in the Portuguese locales. No `bc` code was changed. The issues were that the ISO files used different naming, and also that the files that should have been symlinks were not. I did not catch that because GitHub rendered them the exact same way. ## 2.5.2 This release is a production release. No code was changed, but the build system was changed to allow `CFLAGS` to be given to `CC`, like this: ``` CC="gcc -O3 -march=native" ./configure.sh ``` If this happens, the flags are automatically put into `CFLAGS`, and the compiler is set appropriately. In the example above this means that `CC` will be "gcc" and `CFLAGS` will be "-O3 -march=native". This behavior was added to conform to GNU autotools practices. ## 2.5.1 This is a production release which addresses portability concerns discovered in the `bc` build system. No `bc` code was changed. * Support for Solaris SPARC and AIX were added. * Minor documentations edits were performed. * An option for `configure.sh` was added to disable long options if `getopt_long()` is missing. ## 2.5.0 This is a production release with new translations. No code changed. The translations were contributed by [bugcrazy][15], and they are for Portuguese, both Portugal and Brazil locales. ## 2.4.0 This is a production release primarily aimed at improving `dc`. * A couple of copy and paste errors in the [`dc` manual][10] were fixed. * `dc` startup was optimized by making sure it didn't have to set up `bc`-only things. * The `bc` `&&` and `||` operators were made available to `dc` through the `M` and `m` commands, respectively. * `dc` macros were changed to be tail call-optimized. The last item, tail call optimization, means that if the last thing in a macro is a call to another macro, then the old macro is popped before executing the new macro. This change was made to stop `dc` from consuming more and more memory as macros are executed in a loop. The `q` and `Q` commands still respect the "hidden" macros by way of recording how many macros were removed by tail call optimization. ## 2.3.2 This is a production release meant to fix warnings in the Gentoo `ebuild` by making it possible to disable binary stripping. Other users do *not* need to upgrade. ## 2.3.1 This is a production release. It fixes a bug that caused `-1000000000 < -1` to return `0`. This only happened with negative numbers and only if the value on the left was more negative by a certain amount. That said, this bug *is* a bad bug, and needs to be fixed. **ALL USERS SHOULD UPDATE `bc`**. ## 2.3.0 This is a production release with changes to the build system. ## 2.2.0 This release is a production release. It only has new features and performance improvements. 1. The performance of `sqrt(x)` was improved. 2. The new function `root(x, n)` was added to the extended math library to calculate `n`th roots. 3. The new function `cbrt(x)` was added to the extended math library to calculate cube roots. ## 2.1.3 This is a non-critical release; it just changes the build system, and in non-breaking ways: 1. Linked locale files were changed to link to their sources with a relative link. 2. A bug in `configure.sh` that caused long option parsing to fail under `bash` was fixed. ## 2.1.2 This release is not a critical release. 1. A few codes were added to history. 2. Multiplication was optimized a bit more. 3. Addition and subtraction were both optimized a bit more. ## 2.1.1 This release contains a fix for the test suite made for Linux from Scratch: now the test suite prints `pass` when a test is passed. Other than that, there is no change in this release, so distros and other users do not need to upgrade. ## 2.1.0 This release is a production release. The following bugs were fixed: 1. A `dc` bug that caused stack mishandling was fixed. 2. A warning on OpenBSD was fixed. 3. Bugs in `ctrl+arrow` operations in history were fixed. 4. The ability to paste multiple lines in history was added. 5. A `bc` bug, mishandling of array arguments to functions, was fixed. 6. A crash caused by freeing the wrong pointer was fixed. 7. A `dc` bug where strings, in a rare case, were mishandled in parsing was fixed. In addition, the following changes were made: 1. Division was slightly optimized. 2. An option was added to the build to disable printing of prompts. 3. The special case of empty arguments is now handled. This is to prevent errors in scripts that end up passing empty arguments. 4. A harmless bug was fixed. This bug was that, with the pop instructions (mostly) removed (see below), `bc` would leave extra values on its stack for `void` functions and in a few other cases. These extra items would not affect anything put on the stack and would not cause any sort of crash or even buggy behavior, but they would cause `bc` to take more memory than it needed. On top of the above changes, the following optimizations were added: 1. The need for pop instructions in `bc` was removed. 2. Extra tests on every iteration of the interpreter loop were removed. 3. Updating function and code pointers on every iteration of the interpreter loop was changed to only updating them when necessary. 4. Extra assignments to pointers were removed. Altogether, these changes sped up the interpreter by around 2x. ***NOTE***: This is the last release with new features because this `bc` is now considered complete. From now on, only bug fixes and new translations will be added to this `bc`. ## 2.0.3 This is a production, bug-fix release. Two bugs were fixed in this release: 1. A rare and subtle signal handling bug was fixed. 2. A misbehavior on `0` to a negative power was fixed. The last bug bears some mentioning. When I originally wrote power, I did not thoroughly check its error cases; instead, I had it check if the first number was `0` and then if so, just return `0`. However, `0` to a negative power means that `1` will be divided by `0`, which is an error. I caught this, but only after I stopped being cocky. You see, sometime later, I had noticed that GNU `bc` returned an error, correctly, but I thought it was wrong simply because that's not what my `bc` did. I saw it again later and had a double take. I checked for real, finally, and found out that my `bc` was wrong all along. That was bad on me. But the bug was easy to fix, so it is fixed now. There are two other things in this release: 1. Subtraction was optimized by [Stefan Eßer][14]. 2. Division was also optimized, also by Stefan Eßer. ## 2.0.2 This release contains a fix for a possible overflow in the signal handling. I would be surprised if any users ran into it because it would only happen after 2 billion (`2^31-1`) `SIGINT`'s, but I saw it and had to fix it. ## 2.0.1 This release contains very few things that will apply to any users. 1. A slight bug in `dc`'s interactive mode was fixed. 2. A bug in the test suite that was only triggered on NetBSD was fixed. 3. **The `-P`/`--no-prompt` option** was added for users that do not want a prompt. 4. A `make check` target was added as an alias for `make test`. 5. `dc` got its own read prompt: `?> `. ## 2.0.0 This release is a production release. This release is also a little different from previous releases. From here on out, I do not plan on adding any more features to this `bc`; I believe that it is complete. However, there may be bug fix releases in the future, if I or any others manage to find bugs. This release has only a few new features: 1. `atan2(y, x)` was added to the extended math library as both `a2(y, x)` and `atan2(y, x)`. 2. Locales were fixed. 3. A **POSIX shell-compatible script was added as an alternative to compiling `gen/strgen.c`** on a host machine. More details about making the choice between the two can be found by running `./configure.sh --help` or reading the [build manual][13]. 4. Multiplication was optimized by using **diagonal multiplication**, rather than straight brute force. 5. The `locale_install.sh` script was fixed. 6. `dc` was given the ability to **use the environment variable `DC_ENV_ARGS`**. 7. `dc` was also given the ability to **use the `-i` or `--interactive`** options. 8. Printing the prompt was fixed so that it did not print when it shouldn't. 9. Signal handling was fixed. 10. **Handling of `SIGTERM` and `SIGQUIT`** was fixed. 11. The **built-in functions `maxibase()`, `maxobase()`, and `maxscale()`** (the commands `T`, `U`, `V` in `dc`, respectively) were added to allow scripts to query for the max allowable values of those globals. 12. Some incompatibilities with POSIX were fixed. In addition, this release is `2.0.0` for a big reason: the internal format for numbers changed. They used to be a `char` array. Now, they are an array of larger integers, packing more decimal digits into each integer. This has delivered ***HUGE*** performance improvements, especially for multiplication, division, and power. This `bc` should now be the fastest `bc` available, but I may be wrong. ## 1.2.8 This release contains a fix for a harmless bug (it is harmless in that it still works, but it just copies extra data) in the [`locale_install.sh`][12] script. ## 1.2.7 This version contains fixes for the build on Arch Linux. ## 1.2.6 This release removes the use of `local` in shell scripts because it's not POSIX shell-compatible, and also updates a man page that should have been updated a long time ago but was missed. ## 1.2.5 This release contains some missing locale `*.msg` files. ## 1.2.4 This release contains a few bug fixes and new French translations. ## 1.2.3 This release contains a fix for a bug: use of uninitialized data. Such data was only used when outputting an error message, but I am striving for perfection. As Michelangelo said, "Trifles make perfection, and perfection is no trifle." ## 1.2.2 This release contains fixes for OpenBSD. ## 1.2.1 This release contains bug fixes for some rare bugs. ## 1.2.0 This is a production release. There have been several changes since `1.1.0`: 1. The build system had some changes. 2. Locale support has been added. (Patches welcome for translations.) 3. **The ability to turn `ibase`, `obase`, and `scale` into stacks** was added with the `-g` command-line option. (See the [`bc` manual][9] for more details.) 4. Support for compiling on Mac OSX out of the box was added. 5. The extended math library got `t(x)`, `ceil(x)`, and some aliases. 6. The extended math library also got `r2d(x)` (for converting from radians to degrees) and `d2r(x)` (for converting from degrees to radians). This is to allow using degrees with the standard library. 7. Both calculators now accept numbers in **scientific notation**. See the [`bc` manual][9] and the [`dc` manual][10] for details. 8. Both calculators can **output in either scientific or engineering notation**. See the [`bc` manual][9] and the [`dc` manual][10] for details. 9. Some inefficiencies were removed. 10. Some bugs were fixed. 11. Some bugs in the extended library were fixed. 12. Some defects from [Coverity Scan][11] were fixed. ## 1.1.4 This release contains a fix to the build system that allows it to build on older versions of `glibc`. ## 1.1.3 This release contains a fix for a bug in the test suite where `bc` tests and `dc` tests could not be run in parallel. ## 1.1.2 This release has a fix for a history bug; the down arrow did not work. ## 1.1.1 This release fixes a bug in the `1.1.0` build system. The source is exactly the same. The bug that was fixed was a failure to install if no `EXECSUFFIX` was used. ## 1.1.0 This is a production release. However, many new features were added since `1.0`. 1. **The build system has been changed** to use a custom, POSIX shell-compatible configure script ([`configure.sh`][6]) to generate a POSIX make-compatible `Makefile`, which means that `bc` and `dc` now build out of the box on any POSIX-compatible system. 2. Out-of-memory and output errors now cause the `bc` to report the error, clean up, and die, rather than just reporting and trying to continue. 3. **Strings and constants are now garbage collected** when possible. 4. Signal handling and checking has been made more simple and more thorough. 5. `BcGlobals` was refactored into `BcVm` and `BcVm` was made global. Some procedure names were changed to reflect its difference to everything else. 6. Addition got a speed improvement. 7. Some common code for addition and multiplication was refactored into its own procedure. 8. A bug was removed where `dc` could have been selected, but the internal `#define` that returned `true` for a query about `dc` would not have returned `true`. 9. Useless calls to `bc_num_zero()` were removed. 10. **History support was added.** The history support is based off of a [UTF-8 aware fork][7] of [`linenoise`][8], which has been customized with `bc`'s own data structures and signal handling. 11. Generating C source from the math library now removes tabs from the library, shrinking the size of the executable. 12. The math library was shrunk. 13. Error handling and reporting was improved. 14. Reallocations were reduced by giving access to the request size for each operation. 15. **`abs()` (`b` command for `dc`) was added as a builtin.** 16. Both calculators were tested on FreeBSD. 17. Many obscure parse bugs were fixed. 18. Markdown and man page manuals were added, and the man pages are installed by `make install`. 19. Executable size was reduced, though the added features probably made the executable end up bigger. 20. **GNU-style array references were added as a supported feature.** 21. Allocations were reduced. 22. **New operators were added**: `$` (`$` for `dc`), `@` (`@` for `dc`), `@=`, `<<` (`H` for `dc`), `<<=`, `>>` (`h` for `dc`), and `>>=`. See the [`bc` manual][9] and the [`dc` manual][10] for more details. 23. **An extended math library was added.** This library contains code that makes it so I can replace my desktop calculator with this `bc`. See the [`bc` manual][3] for more details. 24. Support for all capital letters as numbers was added. 25. **Support for GNU-style void functions was added.** 26. A bug fix for improper handling of function parameters was added. 27. Precedence for the or (`||`) operator was changed to match GNU `bc`. 28. `dc` was given an explicit negation command. 29. `dc` was changed to be able to handle strings in arrays. ## 1.1 Release Candidate 3 This release is the eighth release candidate for 1.1, though it is the third release candidate meant as a general release candidate. The new code has not been tested as thoroughly as it should for release. ## 1.1 Release Candidate 2 This release is the seventh release candidate for 1.1, though it is the second release candidate meant as a general release candidate. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 5 This release is the sixth release candidate for 1.1, though it is the fifth release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 4 This release is the fifth release candidate for 1.1, though it is the fourth release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 3 This release is the fourth release candidate for 1.1, though it is the third release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 2 This release is the third release candidate for 1.1, though it is the second release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 1 This release is the second release candidate for 1.1, though it is meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 Release Candidate 1 This is the first release candidate for 1.1. The new code has not been tested as thoroughly as it should for release. ## 1.0 This is the first non-beta release. `bc` is ready for production use. As such, a lot has changed since 0.5. 1. `dc` has been added. It has been tested even more thoroughly than `bc` was for `0.5`. It does not have the `!` command, and for security reasons, it never will, so it is complete. 2. `bc` has been more thoroughly tested. An entire section of the test suite (for both programs) has been added to test for errors. 3. A prompt (`>>> `) has been added for interactive mode, making it easier to see inputs and outputs. 4. Interrupt handling has been improved, including elimination of race conditions (as much as possible). 5. MinGW and [Windows Subsystem for Linux][1] support has been added (see [xstatic][2] for binaries). 6. Memory leaks and errors have been eliminated (as far as ASan and Valgrind can tell). 7. Crashes have been eliminated (as far as [afl][3] can tell). 8. Karatsuba multiplication was added (and thoroughly) tested, speeding up multiplication and power by orders of magnitude. 9. Performance was further enhanced by using a "divmod" function to reduce redundant divisions and by removing superfluous `memset()` calls. 10. To switch between Karatsuba and `O(n^2)` multiplication, the config variable `BC_NUM_KARATSUBA_LEN` was added. It is set to a sane default, but the optimal number can be found with [`karatsuba.py`][4] (requires Python 3) and then configured through `make`. 11. The random math test generator script was changed to Python 3 and improved. `bc` and `dc` have together been run through 30+ million random tests. 12. All known math bugs have been fixed, including out of control memory allocations in `sine` and `cosine` (that was actually a parse bug), certain cases of infinite loop on square root, and slight inaccuracies (as much as possible; see the [README][5]) in transcendental functions. 13. Parsing has been fixed as much as possible. 14. Test coverage was improved to 94.8%. The only paths not covered are ones that happen when `malloc()` or `realloc()` fails. 15. An extension to get the length of an array was added. 16. The boolean not (`!`) had its precedence change to match negation. 17. Data input was hardened. 18. `bc` was made fully compliant with POSIX when the `-s` flag is used or `POSIXLY_CORRECT` is defined. 19. Error handling was improved. 20. `bc` now checks that files it is given are not directories. ## 1.0 Release Candidate 7 This is the seventh release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 6. ## 1.0 Release Candidate 6 This is the sixth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 5. ## 1.0 Release Candidate 5 This is the fifth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 4. ## 1.0 Release Candidate 4 This is the fourth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 3. ## 1.0 Release Candidate 3 This is the third release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 2. ## 1.0 Release Candidate 2 This is the second release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 1. ## 1.0 Release Candidate 1 This is the first Release Candidate for 1.0. `bc` is complete, with `dc`, but it is not tested. ## 0.5 This beta release completes more features, but it is still not complete nor tested as thoroughly as necessary. ## 0.4.1 This beta release fixes a few bugs in 0.4. ## 0.4 This is a beta release. It does not have the complete set of features, and it is not thoroughly tested. [1]: https://docs.microsoft.com/en-us/windows/wsl/install-win10 [2]: https://pkg.musl.cc/bc/ [3]: http://lcamtuf.coredump.cx/afl/ [4]: ./karatsuba.py [5]: ./README.md [6]: ./configure.sh [7]: https://github.com/rain-1/linenoise-mob [8]: https://github.com/antirez/linenoise [9]: ./manuals/bc/A.1.md [10]: ./manuals/dc/A.1.md [11]: https://scan.coverity.com/projects/gavinhoward-bc [12]: ./locale_install.sh [13]: ./manuals/build.md [14]: https://github.com/stesser [15]: https://github.com/bugcrazy [16]: ./manuals/bc/A.1.md#extended-library [17]: https://github.com/skeeto/optparse [18]: https://www.deepl.com/translator [19]: ./manuals/benchmarks.md [20]: https://github.com/apjanke/ronn-ng [21]: https://pandoc.org/ Index: head/contrib/bc/README.md =================================================================== --- head/contrib/bc/README.md (revision 363809) +++ head/contrib/bc/README.md (revision 363810) @@ -1,335 +1,337 @@ # `bc` [![Build Status][13]][14] [![codecov][15]][16] [![Coverity Scan Build Status][17]][18] ***WARNING: This project has moved to [https://git.yzena.com/][20] for [these reasons][21], though GitHub will remain a mirror.*** This is an implementation of the [POSIX `bc` calculator][12] that implements [GNU `bc`][1] extensions, as well as the period (`.`) extension for the BSD flavor of `bc`. For more information, see this `bc`'s full manual. This `bc` also includes an implementation of `dc` in the same binary, accessible via a symbolic link, which implements all FreeBSD and GNU extensions. (If a standalone `dc` binary is desired, `bc` can be copied and renamed to `dc`.) The `!` command is omitted; I believe this poses security concerns and that such functionality is unnecessary. For more information, see the `dc`'s full manual. This `bc` is Free and Open Source Software (FOSS). It is offered under the BSD 2-clause License. Full license text may be found in the [`LICENSE.md`][4] file. ## Prerequisites This `bc` only requires a C99-compatible compiler and a (mostly) POSIX 2008-compatible system with the XSI (X/Open System Interfaces) option group. Since POSIX 2008 with XSI requires the existence of a C99 compiler as `c99`, any POSIX and XSI-compatible system will have everything needed. Systems that are known to work: * Linux * FreeBSD * OpenBSD * NetBSD * Mac OSX * Solaris* (as long as the Solaris version supports POSIX 2008) * AIX Please submit bug reports if this `bc` does not build out of the box on any system besides Windows. If Windows binaries are needed, they can be found at [xstatic][6]. ## Build This `bc` should build unmodified on any POSIX-compliant system. For more complex build requirements than the ones below, see the [build manual][5]. ### Pre-built Binaries It is possible to download pre-compiled binaries for a wide list of platforms, including Linux- and Windows-based systems, from [xstatic][6]. This link always points to the latest release of `bc`. ### Default For the default build with optimization, use the following commands in the root directory: ``` ./configure.sh -O3 make ``` ### One Calculator To only build `bc`, use the following commands: ``` ./configure.sh --disable-dc make ``` To only build `dc`, use the following commands: ``` ./configure.sh --disable-bc make ``` ### Debug For debug builds, use the following commands in the root directory: ``` ./configure.sh -g make ``` ### Install To install, use the following command: ``` make install ``` By default, `bc` and `dc` will be installed in `/usr/local`. For installing in other locations, use the `PREFIX` environment variable when running `configure.sh` or pass the `--prefix=` option to `configure.sh`. See the [build manual][5], or run `./configure.sh --help`, for more details. ### Package and Distro Maintainers #### Recommended Compiler When I ran benchmarks with my `bc` compiled under `clang`, it performed much better than when compiled under `gcc`. I recommend compiling this `bc` with `clang`. I also recommend building this `bc` with C11 if you can because `bc` will detect a C11 compiler and add `_Noreturn` to any relevant function(s). #### Recommended Optimizations I wrote this `bc` with Separation of Concerns, which means that there are many small functions that could be inlined. However, they are often called across file boundaries, and the default optimizer can only look at the current file, which means that they are not inlined. Thus, because of the way this `bc` is built, it will automatically be slower than other `bc` implementations when running scripts with no math. (My `bc`'s math is *much* faster, so any non-trivial script should run faster in my `bc`.) Some, or all, of the difference can be made up with the right optimizations. The optimizations I recommend are: 1. `-O3` 2. `-flto` (link-time optimization) in that order. Link-time optimization, in particular, speeds up the `bc` a lot. This is because when link-time optimization is turned on, the optimizer can look across files and inline *much* more heavily. However, I recommend ***NOT*** using `-march=native`. Doing so will reduce this `bc`'s performance, at least when building with link-time optimization. See the [benchmarks][19] for more details. #### Stripping Binaries By default, non-debug binaries are stripped, but stripping can be disabled with the `-T` option to `configure.sh`. #### Using This `bc` as an Alternative If this `bc` is packaged as an alternative to an already existing `bc` package, it is possible to rename it in the build to prevent name collision. To prepend to the name, just run the following: ``` EXECPREFIX= ./configure.sh ``` To append to the name, just run the following: ``` EXECSUFFIX= ./configure.sh ``` If a package maintainer wishes to add both a prefix and a suffix, that is allowed. **Note**: The suggested name (and package name) when `bc` is not available is `bc-gh`. #### Karatsuba Number Package and distro maintainers have one tool at their disposal to build this `bc` in the optimal configuration: `karatsuba.py`. This script is not a compile-time or runtime prerequisite; it is for package and distro maintainers to run once when a package is being created. It finds the optimal Karatsuba number (see the [algorithms manual][7] for more information) for the machine that it is running on. The easiest way to run this script is with `make karatsuba`. If desired, maintainers can also skip running this script because there is a sane default for the Karatsuba number. ## Status This `bc` is robust. It is well-tested, fuzzed, and fully standards-compliant (though not certified) with POSIX `bc`. The math has been tested with 40+ million random problems, so it is as correct as I can make it. This `bc` can be used as a drop-in replacement for any existing `bc`. This `bc` is also compatible with MinGW toolchains, though history is not supported on Windows. In addition, this `bc` is considered complete; i.e., there will be no more releases with additional features. However, it *is* actively maintained, so if any bugs are found, they will be fixed in new releases. Also, additional translations will also be added as they are provided. ## Comparison to GNU `bc` This `bc` compares favorably to GNU `bc`. * It has more extensions, which make this `bc` more useful for scripting. * This `bc` is a bit more POSIX compliant. * It has a much less buggy parser. The GNU `bc` will give parse errors for what is actually valid `bc` code, or should be. For example, putting an `else` on a new line after a brace can cause GNU `bc` to give a parse error. * This `bc` has fewer crashes. * GNU `bc` calculates the wrong number of significant digits for `length(x)`. * GNU `bc` will sometimes print numbers incorrectly. For example, when running it on the file `tests/bc/power.txt` in this repo, GNU `bc` gets all the right answers, but it fails to wrap the numbers at the proper place when outputting to a file. * This `bc` is faster. (See [Performance](#performance).) ### Performance Because this `bc` packs more than `1` decimal digit per hardware integer, this `bc` is faster than GNU `bc` and can be *much* faster. Full benchmarks can be found at [manuals/benchmarks.md][19]. There is one instance where this `bc` is slower: if scripts are light on math. This is because this `bc`'s intepreter is slightly slower than GNU `bc`, but that is because it is more robust. See the [benchmarks][19]. ## Algorithms To see what algorithms this `bc` uses, see the [algorithms manual][7]. ## Locales Currently, this `bc` only has support for English (and US English), French, German, Portuguese, Dutch, Polish, Russian, Japanese, and Chinese locales. Patches are welcome for translations; use the existing `*.msg` files in `locales/` as a starting point. In addition, patches for improvements are welcome; the last two messages in Portuguese were made with Google Translate, and the Dutch, Polish, Russian, Japanese, and Chinese locales were all generated with [DeepL][22]. The message files provided assume that locales apply to all regions where a language is used, but this might not be true for, e.g., `fr_CA` and `fr_CH`. Any corrections or a confirmation that the current texts are acceptable for those regions would be appreciated, too. ## Other Projects Other projects based on this bc are: * [busybox `bc`][8]. The busybox maintainers have made their own changes, so any bugs in the busybox `bc` should be reported to them. * [toybox `bc`][9]. The maintainer has also made his own changes, so bugs in the toybox `bc` should be reported there. * [FreeBSD `bc`][23]. While the `bc` in FreeBSD is kept up-to-date, it is better - to report bugs there, and the maintainers of the package will contact me if - necessary. + to [report bugs there][24], as well as [submit patches][25], and the + maintainers of the package will contact me if necessary. ## Language This `bc` is written in pure ISO C99, using POSIX 2008 APIs. ## Commit Messages This `bc` uses the commit message guidelines laid out in [this blog post][10]. ## Semantic Versioning This `bc` uses [semantic versioning][11]. ## Contents Items labeled with `(maintainer use only)` are not included in release source tarballs. Files: .gitignore The git ignore file (maintainer use only). .travis.yml The Travis CI file (maintainer use only). codecov.yml The Codecov file (maintainer use only). configure A symlink to configure.sh to make packaging easier. configure.sh The configure script. functions.sh A script with functions used by other scripts. install.sh Install script. karatsuba.py Script to find the optimal Karatsuba number. LICENSE.md A Markdown form of the BSD 2-clause License. link.sh A script to link dc to bc. locale_install.sh A script to install locales, if desired. locale_uninstall.sh A script to uninstall locales. Makefile.in The Makefile template. manpage.sh Script to generate man pages from markdown files. NOTICE.md List of contributors and copyright owners. RELEASE.md A checklist for making a release (maintainer use only). release.sh A script to test for release (maintainer use only). safe-install.sh Safe install script from musl libc. Folders: gen The bc math library, help texts, and code to generate C source. include All header files. locales Locale files, in .msg format. Patches welcome for translations. manuals Manuals for both programs. src All source code. tests All tests. [1]: https://www.gnu.org/software/bc/ [4]: ./LICENSE.md [5]: ./manuals/build.md [6]: https://pkg.musl.cc/bc/ [7]: ./manuals/algorithms.md [8]: https://git.busybox.net/busybox/tree/miscutils/bc.c [9]: https://github.com/landley/toybox/blob/master/toys/pending/bc.c [10]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html [11]: http://semver.org/ [12]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [13]: https://travis-ci.com/gavinhoward/bc.svg?branch=master [14]: https://travis-ci.com/gavinhoward/bc [15]: https://codecov.io/gh/gavinhoward/bc/branch/master/graph/badge.svg [16]: https://codecov.io/gh/gavinhoward/bc [17]: https://img.shields.io/coverity/scan/16609.svg [18]: https://scan.coverity.com/projects/gavinhoward-bc [19]: ./manuals/benchmarks.md [20]: https://git.yzena.com/gavin/bc [21]: https://gavinhoward.com/2020/04/i-am-moving-away-from-github/ [22]: https://www.deepl.com/translator -[23]: https://github.com/freebsd/freebsd/tree/master/contrib/bc +[23]: https://svnweb.freebsd.org/base/head/contrib/bc/ +[24]: https://bugs.freebsd.org/ +[25]: https://reviews.freebsd.org/ Index: head/contrib/bc/include/bc.h =================================================================== --- head/contrib/bc/include/bc.h (revision 363809) +++ head/contrib/bc/include/bc.h (revision 363810) @@ -1,181 +1,178 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Definitions for bc. * */ #ifndef BC_BC_H #define BC_BC_H #if BC_ENABLED #include #include #include #include #include void bc_main(int argc, char **argv); extern const char bc_help[]; extern const char bc_lib[]; extern const char* bc_lib_name; #if BC_ENABLE_EXTRA_MATH extern const char bc_lib2[]; extern const char* bc_lib2_name; #endif // BC_ENABLE_EXTRA_MATH typedef struct BcLexKeyword { uchar data; const char name[9]; } BcLexKeyword; #define BC_LEX_CHAR_MSB(bit) ((bit) << (CHAR_BIT - 1)) #define BC_LEX_KW_POSIX(kw) ((kw)->data & (BC_LEX_CHAR_MSB(1))) #define BC_LEX_KW_LEN(kw) ((size_t) ((kw)->data & ~(BC_LEX_CHAR_MSB(1)))) #define BC_LEX_KW_ENTRY(a, b, c) \ { .data = ((b) & ~(BC_LEX_CHAR_MSB(1))) | BC_LEX_CHAR_MSB(c), .name = a } extern const BcLexKeyword bc_lex_kws[]; extern const size_t bc_lex_kws_len; void bc_lex_token(BcLex *l); #define BC_PARSE_TOP_FLAG_PTR(p) ((uint16_t*) bc_vec_top(&(p)->flags)) #define BC_PARSE_TOP_FLAG(p) (*(BC_PARSE_TOP_FLAG_PTR(p))) #define BC_PARSE_FLAG_BRACE (UINTMAX_C(1)<<0) #define BC_PARSE_BRACE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BRACE) #define BC_PARSE_FLAG_FUNC_INNER (UINTMAX_C(1)<<1) #define BC_PARSE_FUNC_INNER(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_FUNC_INNER) #define BC_PARSE_FLAG_FUNC (UINTMAX_C(1)<<2) #define BC_PARSE_FUNC(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_FUNC) #define BC_PARSE_FLAG_BODY (UINTMAX_C(1)<<3) #define BC_PARSE_BODY(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BODY) #define BC_PARSE_FLAG_LOOP (UINTMAX_C(1)<<4) #define BC_PARSE_LOOP(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_LOOP) #define BC_PARSE_FLAG_LOOP_INNER (UINTMAX_C(1)<<5) #define BC_PARSE_LOOP_INNER(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_LOOP_INNER) #define BC_PARSE_FLAG_IF (UINTMAX_C(1)<<6) #define BC_PARSE_IF(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF) #define BC_PARSE_FLAG_ELSE (UINTMAX_C(1)<<7) #define BC_PARSE_ELSE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_ELSE) #define BC_PARSE_FLAG_IF_END (UINTMAX_C(1)<<8) #define BC_PARSE_IF_END(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF_END) #define BC_PARSE_NO_EXEC(p) ((p)->flags.len != 1 || BC_PARSE_TOP_FLAG(p) != 0) #define BC_PARSE_DELIMITER(t) \ ((t) == BC_LEX_SCOLON || (t) == BC_LEX_NLINE || (t) == BC_LEX_EOF) #define BC_PARSE_BLOCK_STMT(f) \ ((f) & (BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_LOOP_INNER)) #define BC_PARSE_OP(p, l) (((p) & ~(BC_LEX_CHAR_MSB(1))) | (BC_LEX_CHAR_MSB(l))) #define BC_PARSE_OP_DATA(t) bc_parse_ops[((t) - BC_LEX_OP_INC)] #define BC_PARSE_OP_LEFT(op) (BC_PARSE_OP_DATA(op) & BC_LEX_CHAR_MSB(1)) #define BC_PARSE_OP_PREC(op) (BC_PARSE_OP_DATA(op) & ~(BC_LEX_CHAR_MSB(1))) #define BC_PARSE_EXPR_ENTRY(e1, e2, e3, e4, e5, e6, e7, e8) \ ((UINTMAX_C(e1) << 7) | (UINTMAX_C(e2) << 6) | (UINTMAX_C(e3) << 5) | \ (UINTMAX_C(e4) << 4) | (UINTMAX_C(e5) << 3) | (UINTMAX_C(e6) << 2) | \ (UINTMAX_C(e7) << 1) | (UINTMAX_C(e8) << 0)) #define BC_PARSE_EXPR(i) \ (bc_parse_exprs[(((i) & (uchar) ~(0x07)) >> 3)] & (1 << (7 - ((i) & 0x07)))) #define BC_PARSE_TOP_OP(p) (*((BcLexType*) bc_vec_top(&(p)->ops))) #define BC_PARSE_LEAF(prev, bin_last, rparen) \ (!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev))) #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_INST_VAR(t) \ ((t) >= BC_INST_VAR && (t) <= BC_INST_SEED && (t) != BC_INST_ARRAY) #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_INST_VAR(t) \ ((t) >= BC_INST_VAR && (t) <= BC_INST_SCALE && (t) != BC_INST_ARRAY) #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_PREV_PREFIX(p) \ ((p) >= BC_INST_NEG && (p) <= BC_INST_BOOL_NOT) #define BC_PARSE_OP_PREFIX(t) ((t) == BC_LEX_OP_BOOL_NOT || (t) == BC_LEX_NEG) // We can calculate the conversion between tokens and exprs by subtracting the // position of the first operator in the lex enum and adding the position of // the first in the expr enum. Note: This only works for binary operators. #define BC_PARSE_TOKEN_INST(t) ((uchar) ((t) - BC_LEX_NEG + BC_INST_NEG)) typedef enum BcParseStatus { BC_PARSE_STATUS_SUCCESS, BC_PARSE_STATUS_EMPTY_EXPR, } BcParseStatus; void bc_parse_expr(BcParse *p, uint8_t flags); void bc_parse_parse(BcParse *p); void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next); -// This is necessary to clear up for if statements at the end of files. -void bc_parse_noElse(BcParse *p); - extern const char bc_sig_msg[]; extern const uchar bc_sig_msg_len; extern const char* const bc_parse_const1; extern const uint8_t bc_parse_exprs[]; extern const uchar bc_parse_ops[]; extern const BcParseNext bc_parse_next_expr; extern const BcParseNext bc_parse_next_param; extern const BcParseNext bc_parse_next_print; extern const BcParseNext bc_parse_next_rel; extern const BcParseNext bc_parse_next_elem; extern const BcParseNext bc_parse_next_for; extern const BcParseNext bc_parse_next_read; #endif // BC_ENABLED #endif // BC_BC_H Index: head/contrib/bc/include/vm.h =================================================================== --- head/contrib/bc/include/vm.h (revision 363809) +++ head/contrib/bc/include/vm.h (revision 363810) @@ -1,392 +1,386 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Definitions for bc's VM. * */ #ifndef BC_VM_H #define BC_VM_H #include #include #include #if BC_ENABLE_NLS # ifdef _WIN32 # error NLS is not supported on Windows. # endif // _WIN32 #include #endif // BC_ENABLE_NLS #include #include #include #include #include #include #if !BC_ENABLED && !DC_ENABLED #error Must define BC_ENABLED, DC_ENABLED, or both #endif // CHAR_BIT must be at least 6. #if CHAR_BIT < 6 #error CHAR_BIT must be at least 6. #endif #ifndef BC_ENABLE_NLS #define BC_ENABLE_NLS (0) #endif // BC_ENABLE_NLS #ifndef MAINEXEC #define MAINEXEC bc #endif #ifndef EXECPREFIX #define EXECPREFIX #endif #define GEN_STR(V) #V #define GEN_STR2(V) GEN_STR(V) #define BC_VERSION GEN_STR2(VERSION) #define BC_EXECPREFIX GEN_STR2(EXECPREFIX) #define BC_MAINEXEC GEN_STR2(MAINEXEC) // Windows has deprecated isatty(). #ifdef _WIN32 #define isatty _isatty #endif // _WIN32 #if DC_ENABLED #define DC_FLAG_X (UINTMAX_C(1)<<0) #endif // DC_ENABLED #if BC_ENABLED #define BC_FLAG_W (UINTMAX_C(1)<<1) #define BC_FLAG_S (UINTMAX_C(1)<<2) #define BC_FLAG_L (UINTMAX_C(1)<<3) #define BC_FLAG_G (UINTMAX_C(1)<<4) #endif // BC_ENABLED -#define BC_FLAG_Q (UINTMAX_C(1)<<5) -#define BC_FLAG_I (UINTMAX_C(1)<<6) -#define BC_FLAG_P (UINTMAX_C(1)<<7) -#define BC_FLAG_TTYIN (UINTMAX_C(1)<<8) -#define BC_FLAG_TTY (UINTMAX_C(1)<<9) +#define BC_FLAG_I (UINTMAX_C(1)<<5) +#define BC_FLAG_P (UINTMAX_C(1)<<6) +#define BC_FLAG_TTYIN (UINTMAX_C(1)<<7) +#define BC_FLAG_TTY (UINTMAX_C(1)<<8) #define BC_TTYIN (vm.flags & BC_FLAG_TTYIN) #define BC_TTY (vm.flags & BC_FLAG_TTY) #if BC_ENABLED #define BC_S (vm.flags & BC_FLAG_S) #define BC_W (vm.flags & BC_FLAG_W) #define BC_L (vm.flags & BC_FLAG_L) #define BC_G (vm.flags & BC_FLAG_G) #endif // BC_ENABLED #if DC_ENABLED #define DC_X (vm.flags & DC_FLAG_X) #endif // DC_ENABLED #define BC_I (vm.flags & BC_FLAG_I) #define BC_P (vm.flags & BC_FLAG_P) #if BC_ENABLED #define BC_IS_POSIX (BC_S || BC_W) #if DC_ENABLED #define BC_IS_BC (vm.name[0] != 'd') #define BC_IS_DC (vm.name[0] == 'd') #else // DC_ENABLED #define BC_IS_BC (1) #define BC_IS_DC (0) #endif // DC_ENABLED #else // BC_ENABLED #define BC_IS_POSIX (0) #define BC_IS_BC (0) #define BC_IS_DC (1) #endif // BC_ENABLED #if BC_ENABLED #define BC_USE_PROMPT (!BC_P && BC_TTY && !BC_IS_POSIX) #else // BC_ENABLED #define BC_USE_PROMPT (!BC_P && BC_TTY) #endif // BC_ENABLED #define BC_MAX(a, b) ((a) > (b) ? (a) : (b)) #define BC_MIN(a, b) ((a) < (b) ? (a) : (b)) #define BC_MAX_OBASE ((BcBigDig) (BC_BASE_POW)) #define BC_MAX_DIM ((BcBigDig) (SIZE_MAX - 1)) #define BC_MAX_SCALE ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1)) #define BC_MAX_STRING ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1)) #define BC_MAX_NAME BC_MAX_STRING #define BC_MAX_NUM BC_MAX_SCALE #if BC_ENABLE_EXTRA_MATH #define BC_MAX_RAND ((BcBigDig) (((BcRand) 0) - 1)) #endif // BC_ENABLE_EXTRA_MATH #define BC_MAX_EXP ((ulong) (BC_NUM_BIGDIG_MAX)) #define BC_MAX_VARS ((ulong) (SIZE_MAX - 1)) #if BC_DEBUG_CODE #define BC_VM_JMP bc_vm_jmp(__func__) #else // BC_DEBUG_CODE #define BC_VM_JMP bc_vm_jmp() #endif // BC_DEBUG_CODE #define BC_SIG_EXC \ BC_UNLIKELY(vm.status != (sig_atomic_t) BC_STATUS_SUCCESS || vm.sig) #define BC_NO_SIG_EXC \ BC_LIKELY(vm.status == (sig_atomic_t) BC_STATUS_SUCCESS && !vm.sig) #ifndef NDEBUG #define BC_SIG_ASSERT_LOCKED do { assert(vm.sig_lock); } while (0) #define BC_SIG_ASSERT_NOT_LOCKED do { assert(vm.sig_lock == 0); } while (0) #else // NDEBUG #define BC_SIG_ASSERT_LOCKED #define BC_SIG_ASSERT_NOT_LOCKED #endif // NDEBUG #define BC_SIG_LOCK \ do { \ BC_SIG_ASSERT_NOT_LOCKED; \ vm.sig_lock = 1; \ } while (0) #define BC_SIG_UNLOCK \ do { \ BC_SIG_ASSERT_LOCKED; \ vm.sig_lock = 0; \ if (BC_SIG_EXC) BC_VM_JMP; \ } while (0) #define BC_SIG_MAYLOCK \ do { \ vm.sig_lock = 1; \ } while (0) #define BC_SIG_MAYUNLOCK \ do { \ vm.sig_lock = 0; \ if (BC_SIG_EXC) BC_VM_JMP; \ } while (0) #define BC_SIG_TRYLOCK(v) \ do { \ v = vm.sig_lock; \ vm.sig_lock = 1; \ } while (0) #define BC_SIG_TRYUNLOCK(v) \ do { \ vm.sig_lock = (v); \ if (!(v) && BC_SIG_EXC) BC_VM_JMP; \ } while (0) #define BC_SETJMP(l) \ do { \ sigjmp_buf sjb; \ BC_SIG_LOCK; \ if (sigsetjmp(sjb, 0)) { \ assert(BC_SIG_EXC); \ goto l; \ } \ bc_vec_push(&vm.jmp_bufs, &sjb); \ BC_SIG_UNLOCK; \ } while (0) #define BC_SETJMP_LOCKED(l) \ do { \ sigjmp_buf sjb; \ BC_SIG_ASSERT_LOCKED; \ if (sigsetjmp(sjb, 0)) { \ assert(BC_SIG_EXC); \ goto l; \ } \ bc_vec_push(&vm.jmp_bufs, &sjb); \ } while (0) #define BC_LONGJMP_CONT \ do { \ BC_SIG_ASSERT_LOCKED; \ if (!vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); \ BC_SIG_UNLOCK; \ } while (0) #define BC_UNSETJMP \ do { \ BC_SIG_ASSERT_LOCKED; \ bc_vec_pop(&vm.jmp_bufs); \ } while (0) #define BC_LONGJMP_STOP \ do { \ vm.sig_pop = 0; \ vm.sig = 0; \ } while (0) #define BC_VM_BUF_SIZE (1<<12) #define BC_VM_STDOUT_BUF_SIZE (1<<11) #define BC_VM_STDERR_BUF_SIZE (1<<10) #define BC_VM_STDIN_BUF_SIZE (BC_VM_STDERR_BUF_SIZE - 1) #define BC_VM_SAFE_RESULT(r) ((r)->t >= BC_RESULT_TEMP) #define bc_vm_err(e) (bc_vm_error((e), 0)) #define bc_vm_verr(e, ...) (bc_vm_error((e), 0, __VA_ARGS__)) #define BC_STATUS_IS_ERROR(s) \ ((s) >= BC_STATUS_ERROR_MATH && (s) <= BC_STATUS_ERROR_FATAL) #define BC_VM_INVALID_CATALOG ((nl_catd) -1) -// dc does not use is_stdin. -#if !BC_ENABLED -#define bc_vm_process(text, is_stdin) bc_vm_process(text) -#else // BC_ENABLED -#endif // BC_ENABLED - typedef struct BcVm { volatile sig_atomic_t status; volatile sig_atomic_t sig_pop; BcParse prs; BcProgram prog; BcVec jmp_bufs; BcVec temps; const char* file; const char *sigmsg; volatile sig_atomic_t sig_lock; volatile sig_atomic_t sig; uchar siglen; uchar read_ret; uint16_t flags; uint16_t nchars; uint16_t line_len; + bool no_exit_exprs; bool eof; BcBigDig maxes[BC_PROG_GLOBALS_LEN + BC_ENABLE_EXTRA_MATH]; BcVec files; BcVec exprs; const char *name; const char *help; #if BC_ENABLE_HISTORY BcHistory history; #endif // BC_ENABLE_HISTORY BcLexNext next; BcParseParse parse; BcParseExpr expr; const char *func_header; const char *err_ids[BC_ERR_IDX_NELEMS + BC_ENABLED]; const char *err_msgs[BC_ERROR_NELEMS]; const char *locale; BcBigDig last_base; BcBigDig last_pow; BcBigDig last_exp; BcBigDig last_rem; char *env_args_buffer; BcVec env_args; BcNum max; BcDig max_num[BC_NUM_BIGDIG_LOG10]; BcFile fout; BcFile ferr; #if BC_ENABLE_NLS nl_catd catalog; #endif // BC_ENABLE_NLS char *buf; size_t buf_len; } BcVm; void bc_vm_info(const char* const help); void bc_vm_boot(int argc, char *argv[], const char *env_len, - const char* const env_args, const char* env_exp_quit); + const char* const env_args); void bc_vm_shutdown(void); void bc_vm_printf(const char *fmt, ...); void bc_vm_putchar(int c); size_t bc_vm_arraySize(size_t n, size_t size); size_t bc_vm_growSize(size_t a, size_t b); void* bc_vm_malloc(size_t n); void* bc_vm_realloc(void *ptr, size_t n); char* bc_vm_strdup(const char *str); #if BC_DEBUG_CODE void bc_vm_jmp(const char *f); #else // BC_DEBUG_CODE void bc_vm_jmp(void); #endif // BC_DEBUG_CODE void bc_vm_error(BcError e, size_t line, ...); extern const char bc_copyright[]; extern const char* const bc_err_line; extern const char* const bc_err_func_header; extern const char *bc_errs[]; extern const uchar bc_err_ids[]; extern const char* const bc_err_msgs[]; extern BcVm vm; extern char output_bufs[BC_VM_BUF_SIZE]; #endif // BC_VM_H Index: head/contrib/bc/manuals/bc/A.1 =================================================================== --- head/contrib/bc/manuals/bc/A.1 (revision 363809) +++ head/contrib/bc/manuals/bc/A.1 (revision 363810) @@ -1,2099 +1,2092 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/A.1.md =================================================================== --- head/contrib/bc/manuals/bc/A.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/A.1.md (revision 363810) @@ -1,1697 +1,1691 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/E.1 =================================================================== --- head/contrib/bc/manuals/bc/E.1 (revision 363809) +++ head/contrib/bc/manuals/bc/E.1 (revision 363810) @@ -1,1341 +1,1334 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/E.1.md =================================================================== --- head/contrib/bc/manuals/bc/E.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/E.1.md (revision 363810) @@ -1,1091 +1,1085 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/EH.1 =================================================================== --- head/contrib/bc/manuals/bc/EH.1 (revision 363809) +++ head/contrib/bc/manuals/bc/EH.1 (revision 363810) @@ -1,1323 +1,1316 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/EH.1.md =================================================================== --- head/contrib/bc/manuals/bc/EH.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/EH.1.md (revision 363810) @@ -1,1075 +1,1069 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/EHN.1 =================================================================== --- head/contrib/bc/manuals/bc/EHN.1 (revision 363809) +++ head/contrib/bc/manuals/bc/EHN.1 (revision 363810) @@ -1,1316 +1,1309 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/EHN.1.md =================================================================== --- head/contrib/bc/manuals/bc/EHN.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/EHN.1.md (revision 363810) @@ -1,1067 +1,1061 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/EHNP.1 =================================================================== --- head/contrib/bc/manuals/bc/EHNP.1 (revision 363809) +++ head/contrib/bc/manuals/bc/EHNP.1 (revision 363810) @@ -1,1309 +1,1302 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/EHNP.1.md =================================================================== --- head/contrib/bc/manuals/bc/EHNP.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/EHNP.1.md (revision 363810) @@ -1,1061 +1,1055 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/EHP.1 =================================================================== --- head/contrib/bc/manuals/bc/EHP.1 (revision 363809) +++ head/contrib/bc/manuals/bc/EHP.1 (revision 363810) @@ -1,1316 +1,1309 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/EHP.1.md =================================================================== --- head/contrib/bc/manuals/bc/EHP.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/EHP.1.md (revision 363810) @@ -1,1069 +1,1063 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/EN.1 =================================================================== --- head/contrib/bc/manuals/bc/EN.1 (revision 363809) +++ head/contrib/bc/manuals/bc/EN.1 (revision 363810) @@ -1,1334 +1,1327 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/EN.1.md =================================================================== --- head/contrib/bc/manuals/bc/EN.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/EN.1.md (revision 363810) @@ -1,1083 +1,1077 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/ENP.1 =================================================================== --- head/contrib/bc/manuals/bc/ENP.1 (revision 363809) +++ head/contrib/bc/manuals/bc/ENP.1 (revision 363810) @@ -1,1327 +1,1320 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/ENP.1.md =================================================================== --- head/contrib/bc/manuals/bc/ENP.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/ENP.1.md (revision 363810) @@ -1,1077 +1,1071 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/EP.1 =================================================================== --- head/contrib/bc/manuals/bc/EP.1 (revision 363809) +++ head/contrib/bc/manuals/bc/EP.1 (revision 363810) @@ -1,1334 +1,1327 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] .IP .nf \f[C] Turns\ the\ globals\ **ibase**,\ **obase**,\ and\ **scale**\ into\ stacks. This\ has\ the\ effect\ that\ a\ copy\ of\ the\ current\ value\ of\ all\ three\ are\ pushed onto\ a\ stack\ for\ every\ function\ call,\ as\ well\ as\ popped\ when\ every\ function returns.\ This\ means\ that\ functions\ can\ assign\ to\ any\ and\ all\ of\ those globals\ without\ worrying\ that\ the\ change\ will\ affect\ other\ functions. Thus,\ a\ hypothetical\ function\ named\ **output(x,b)**\ that\ simply\ printed **x**\ in\ base\ **b**\ could\ be\ written\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ } instead\ of\ like\ this: \ \ \ \ define\ void\ output(x,\ b)\ { \ \ \ \ \ \ \ \ auto\ c \ \ \ \ \ \ \ \ c=obase \ \ \ \ \ \ \ \ obase=b \ \ \ \ \ \ \ \ x \ \ \ \ \ \ \ \ obase=c \ \ \ \ } This\ makes\ writing\ functions\ much\ easier. However,\ since\ using\ this\ flag\ means\ that\ functions\ cannot\ set\ **ibase**, **obase**,\ or\ **scale**\ globally,\ functions\ that\ are\ made\ to\ do\ so\ cannot work\ anymore.\ There\ are\ two\ possible\ use\ cases\ for\ that,\ and\ each\ has\ a solution. First,\ if\ a\ function\ is\ called\ on\ startup\ to\ turn\ bc(1)\ into\ a\ number converter,\ it\ is\ possible\ to\ replace\ that\ capability\ with\ various\ shell aliases.\ Examples: \ \ \ \ alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" \ \ \ \ alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" Second,\ if\ the\ purpose\ of\ a\ function\ is\ to\ set\ **ibase**,\ **obase**,\ or **scale**\ globally\ for\ any\ other\ purpose,\ it\ could\ be\ split\ into\ one\ to three\ functions\ (based\ on\ how\ many\ globals\ it\ sets)\ and\ each\ of\ those functions\ could\ return\ the\ desired\ value\ for\ a\ global. If\ the\ behavior\ of\ this\ option\ is\ desired\ for\ every\ run\ of\ bc(1),\ then\ users could\ make\ sure\ to\ define\ **BC_ENV_ARGS**\ and\ include\ this\ option\ (see\ the **ENVIRONMENT\ VARIABLES**\ section\ for\ more\ details). If\ **\-s**,\ **\-w**,\ or\ any\ equivalents\ are\ used,\ this\ option\ is\ ignored. This\ is\ a\ **non\-portable\ extension**. \f[] .fi .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the library, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Number 6 is a \f[B]non\-portable extension\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator and the corresponding assignment operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/EP.1.md =================================================================== --- head/contrib/bc/manuals/bc/EP.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/EP.1.md (revision 363810) @@ -1,1085 +1,1079 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The min allowable value for **obase** is **2**. Values are output in the specified base. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **=** **+=** **-=** **\*=** **/=** **%=** **\^=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/H.1 =================================================================== --- head/contrib/bc/manuals/bc/H.1 (revision 363809) +++ head/contrib/bc/manuals/bc/H.1 (revision 363810) @@ -1,2079 +1,2072 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/H.1.md =================================================================== --- head/contrib/bc/manuals/bc/H.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/H.1.md (revision 363810) @@ -1,1680 +1,1674 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/HN.1 =================================================================== --- head/contrib/bc/manuals/bc/HN.1 (revision 363809) +++ head/contrib/bc/manuals/bc/HN.1 (revision 363810) @@ -1,2072 +1,2065 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/HN.1.md =================================================================== --- head/contrib/bc/manuals/bc/HN.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/HN.1.md (revision 363810) @@ -1,1672 +1,1666 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/HNP.1 =================================================================== --- head/contrib/bc/manuals/bc/HNP.1 (revision 363809) +++ head/contrib/bc/manuals/bc/HNP.1 (revision 363810) @@ -1,2065 +1,2058 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/HNP.1.md =================================================================== --- head/contrib/bc/manuals/bc/HNP.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/HNP.1.md (revision 363810) @@ -1,1666 +1,1660 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/HP.1 =================================================================== --- head/contrib/bc/manuals/bc/HP.1 (revision 363809) +++ head/contrib/bc/manuals/bc/HP.1 (revision 363810) @@ -1,2072 +1,2065 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/HP.1.md =================================================================== --- head/contrib/bc/manuals/bc/HP.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/HP.1.md (revision 363810) @@ -1,1674 +1,1668 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/N.1 =================================================================== --- head/contrib/bc/manuals/bc/N.1 (revision 363809) +++ head/contrib/bc/manuals/bc/N.1 (revision 363810) @@ -1,2092 +1,2085 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in bc(1). Most of those users would want to put this option in \f[B]BC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/N.1.md =================================================================== --- head/contrib/bc/manuals/bc/N.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/N.1.md (revision 363810) @@ -1,1689 +1,1683 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/NP.1 =================================================================== --- head/contrib/bc/manuals/bc/NP.1 (revision 363809) +++ head/contrib/bc/manuals/bc/NP.1 (revision 363810) @@ -1,2085 +1,2078 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/NP.1.md =================================================================== --- head/contrib/bc/manuals/bc/NP.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/NP.1.md (revision 363810) @@ -1,1683 +1,1677 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc/P.1 =================================================================== --- head/contrib/bc/manuals/bc/P.1 (revision 363809) +++ head/contrib/bc/manuals/bc/P.1 (revision 363810) @@ -1,2092 +1,2085 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc \- arbitrary\-precision arithmetic language and calculator .SH SYNOPSIS .PP \f[B]bc\f[] [\f[B]\-ghilPqsvVw\f[]] [\f[B]\-\-global\-stacks\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-mathlib\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-quiet\f[]] [\f[B]\-\-standard\f[]] [\f[B]\-\-warn\f[]] [\f[B]\-\-version\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is here (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html).) The language provides unlimited precision decimal arithmetic and is somewhat C\-like, but there are differences. Such differences will be noted in this document. .PP After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from \f[B]stdin\f[]. .PP This bc(1) is a drop\-in replacement for \f[I]any\f[] bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP .B \f[B]\-g\f[], \f[B]\-\-global\-stacks\f[] Turns the globals \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[] into stacks. .RS .PP This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named \f[B]output(x,b)\f[] that simply printed \f[B]x\f[] in base \f[B]b\f[] could be written like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ obase=b \ \ \ \ x } \f[] .fi .PP instead of like this: .IP .nf \f[C] define\ void\ output(x,\ b)\ { \ \ \ \ auto\ c \ \ \ \ c=obase \ \ \ \ obase=b \ \ \ \ x \ \ \ \ obase=c } \f[] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[]: the function \f[B]output(x,b)\f[] exists in the extended math library. See the \f[B]LIBRARY\f[] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. .PP First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: .IP .nf \f[C] alias\ d2o="bc\ \-e\ ibase=A\ \-e\ obase=8" alias\ h2b="bc\ \-e\ ibase=G\ \-e\ obase=2" \f[] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], or \f[B]seed\f[] globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. .PP For functions that set \f[B]seed\f[], the value assigned to \f[B]seed\f[] is not propagated to parent functions. This means that the sequence of pseudo\-random numbers that they see will not be the same sequence of pseudo\-random numbers that any parent sees. This is only the case once \f[B]seed\f[] has been set. .PP If a function desires to not affect the sequence of pseudo\-random numbers of its parents, but wants to use the same \f[B]seed\f[], it can use the following line: .IP .nf \f[C] seed\ =\ seed \f[] .fi .PP If the behavior of this option is desired for every run of bc(1), then users could make sure to define \f[B]BC_ENV_ARGS\f[] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[] section for more details). .PP If \f[B]\-s\f[], \f[B]\-w\f[], or any equivalents are used, this option is ignored. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-l\f[], \f[B]\-\-mathlib\f[] Sets \f[B]scale\f[] (see the \f[B]SYNTAX\f[] section) to \f[B]20\f[] and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. .RS .PP To learn what is in the libraries, see the \f[B]LIBRARY\f[] section. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-q\f[], \f[B]\-\-quiet\f[] -Do not print copyright header. -bc(1) will also suppress the header in non\-interactive mode. +This option is for compatibility with the GNU +bc(1) (https://www.gnu.org/software/bc/); it is a no\-op. +Without this option, GNU bc(1) prints a copyright header. +This bc(1) only prints the copyright header if one or more of the +\f[B]\-v\f[], \f[B]\-V\f[], or \f[B]\-\-version\f[] options are given. .RS .PP -This is mostly for compatibility with the GNU -bc(1) (https://www.gnu.org/software/bc/). -.PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-s\f[], \f[B]\-\-standard\f[] Process exactly the language defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) and error if any extensions are used. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-w\f[], \f[B]\-\-warn\f[] Like \f[B]\-s\f[] and \f[B]\-\-standard\f[], except that warnings (and not errors) are printed for non\-standard extensions and execution continues normally. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the expressions and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other bc(1) implementations, this option causes the program to -execute the files and then exit. -This bc(1) does not, unless the \f[B]BC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, bc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]bc >&\-\f[], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]bc 2>&\-\f[], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other bc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP The syntax for bc(1) programs is mostly C\-like, with some differences. This bc(1) follows the POSIX standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. .PP In the sections below, \f[B]E\f[] means expression, \f[B]S\f[] means statement, and \f[B]I\f[] means identifier. .PP Identifiers (\f[B]I\f[]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX\-1\f[]) of lowercase letters (\f[B]a\-z\f[]), digits (\f[B]0\-9\f[]), and underscores (\f[B]_\f[]). The regex is \f[B][a\-z][a\-z0\-9_]*\f[]. Identifiers with more than one character (letter) are a \f[B]non\-portable extension\f[]. .PP \f[B]ibase\f[] is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. If the \f[B]\-s\f[] (\f[B]\-\-standard\f[]) and \f[B]\-w\f[] (\f[B]\-\-warn\f[]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[] is \f[B]36\f[]. Otherwise, it is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in bc(1) programs with the \f[B]maxibase()\f[] built\-in function. .PP \f[B]obase\f[] is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]BC_BASE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxobase()\f[] built\-in function. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] is \f[B]BC_SCALE_MAX\f[] and can be queried in bc(1) programs with the \f[B]maxscale()\f[] built\-in function. .PP bc(1) has both \f[I]global\f[] variables and \f[I]local\f[] variables. All \f[I]local\f[] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[] list of a function (see the \f[B]FUNCTIONS\f[] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[] list, it is assumed to be \f[I]global\f[]. If a parent function has a \f[I]local\f[] variable version of a variable that a child function considers \f[I]global\f[], the value of that \f[I]global\f[] variable in the child function is the value of the variable in the parent function, not the value of the actual \f[I]global\f[] variable. .PP All of the above applies to arrays as well. .PP The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator \f[I]and\f[] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[]. A single dot (\f[B].\f[]) may also be used as a synonym for \f[B]last\f[]. These are \f[B]non\-portable extensions\f[]. .PP Either semicolons or newlines may separate statements. .SS Comments .PP There are two kinds of comments: .IP "1." 3 Block comments are enclosed in \f[B]/*\f[] and \f[B]*/\f[]. .IP "2." 3 Line comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[] .IP "2." 3 Array Elements: \f[B]I[E]\f[] .IP "3." 3 \f[B]ibase\f[] .IP "4." 3 \f[B]obase\f[] .IP "5." 3 \f[B]scale\f[] .IP "6." 3 \f[B]seed\f[] .IP "7." 3 \f[B]last\f[] or a single dot (\f[B].\f[]) .PP Numbers 6 and 7 are \f[B]non\-portable extensions\f[]. .PP The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] value is assigned to \f[B]seed\f[] and used again, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers as it did when the \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if \f[B]seed\f[] is queried again immediately. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will \f[I]not\f[] produce unique sequences of pseudo\-random numbers. The value of \f[B]seed\f[] will change after any use of the \f[B]rand()\f[] and \f[B]irand(E)\f[] operands (see the \f[I]Operands\f[] subsection below), except if the parameter passed to \f[B]irand(E)\f[] is \f[B]0\f[], \f[B]1\f[], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the \f[B]FUNCTIONS\f[] section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. .PP Named expressions are required as the operand of \f[B]increment\f[]/\f[B]decrement\f[] operators and as the left side of \f[B]assignment\f[] operators (see the \f[I]Operators\f[] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[]). .IP " 3." 4 \f[B](E)\f[]: The value of \f[B]E\f[] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[]: The square root of \f[B]E\f[]. \f[B]E\f[] must be non\-negative. .IP " 5." 4 \f[B]length(E)\f[]: The number of significant decimal digits in \f[B]E\f[]. .IP " 6." 4 \f[B]length(I[])\f[]: The number of elements in the array \f[B]I\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 7." 4 \f[B]scale(E)\f[]: The \f[I]scale\f[] of \f[B]E\f[]. .IP " 8." 4 \f[B]abs(E)\f[]: The absolute value of \f[B]E\f[]. This is a \f[B]non\-portable extension\f[]. .IP " 9." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a non\-\f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[]: Reads a line from \f[B]stdin\f[] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[] operand. This is a \f[B]non\-portable extension\f[]. .IP "11." 4 \f[B]maxibase()\f[]: The max allowable \f[B]ibase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "12." 4 \f[B]maxobase()\f[]: The max allowable \f[B]obase\f[]. This is a \f[B]non\-portable extension\f[]. .IP "13." 4 \f[B]maxscale()\f[]: The max allowable \f[B]scale\f[]. This is a \f[B]non\-portable extension\f[]. .IP "14." 4 \f[B]rand()\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and \f[B]BC_RAND_MAX\f[] (inclusive). Using this operand will change the value of \f[B]seed\f[]. This is a \f[B]non\-portable extension\f[]. .IP "15." 4 \f[B]irand(E)\f[]: A pseudo\-random integer between \f[B]0\f[] (inclusive) and the value of \f[B]E\f[] (exclusive). If \f[B]E\f[] is negative or is a non\-integer (\f[B]E\f[]\[aq]s \f[I]scale\f[] is not \f[B]0\f[]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If \f[B]E\f[] is larger than \f[B]BC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of \f[B]seed\f[], unless the value of \f[B]E\f[] is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. This is a \f[B]non\-portable extension\f[]. .IP "16." 4 \f[B]maxrand()\f[]: The max integer returned by \f[B]rand()\f[]. This is a \f[B]non\-portable extension\f[]. .PP The integers generated by \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with \f[B]rand()\f[] and \f[B]irand(E)\f[] are guaranteed to \f[I]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[I]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]Z\f[] alone always equals decimal \f[B]35\f[]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e\-3\f[] is equal to \f[B]0.0042890\f[]. .PP Using scientific notation is an error or warning if the \f[B]\-s\f[] or \f[B]\-w\f[], respectively, command\-line options (or equivalents) are given. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and bc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if bc(1) is given the number string \f[B]10e\-4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SS Operators .PP The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. .TP .B \f[B]++\f[] \f[B]\-\-\f[] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[], \f[B]decrement\f[] .RE .TP .B \f[B]\-\f[] \f[B]!\f[] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[], \f[B]boolean not\f[] .RE .TP .B \f[B]$\f[] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[] .RE .TP .B \f[B]\@\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[] .RE .TP .B \f[B]^\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[] .RE .TP .B \f[B]*\f[] \f[B]/\f[] \f[B]%\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[], \f[B]divide\f[], \f[B]modulus\f[] .RE .TP .B \f[B]+\f[] \f[B]\-\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[], \f[B]subtract\f[] .RE .TP .B \f[B]<<\f[] \f[B]>>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[], \f[B]shift right\f[] .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[] .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[] .RE .TP .B \f[B]&&\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[] .RE .TP .B \f[B]||\f[] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[] .RE .PP The operators will be described in more detail below. .TP .B \f[B]++\f[] \f[B]\-\-\f[] The prefix and postfix \f[B]increment\f[] and \f[B]decrement\f[] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP .B \f[B]\-\f[] The \f[B]negation\f[] operator returns \f[B]0\f[] if a user attempts to negate any expression with the value \f[B]0\f[]. Otherwise, a copy of the expression with its sign flipped is returned. .RS .RE .TP .B \f[B]!\f[] The \f[B]boolean not\f[] operator returns \f[B]1\f[] if the expression is \f[B]0\f[], or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The \f[B]truncation\f[] operator returns a copy of the given expression with all of its \f[I]scale\f[] removed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] The \f[B]set precision\f[] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[] equal to the value of the second expression. That could either mean that the number is returned without change (if the \f[I]scale\f[] of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] The \f[B]power\f[] operator (not the \f[B]exclusive or\f[] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. .RS .PP The second expression must be an integer (no \f[I]scale\f[]), and if it is negative, the first value must be non\-zero. .RE .TP .B \f[B]*\f[] The \f[B]multiply\f[] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The \f[B]divide\f[] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[] of the result shall be the value of \f[B]scale\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]%\f[] The \f[B]modulus\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and evaluates them by 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[] and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .RS .PP The second expression must be non\-zero. .RE .TP .B \f[B]+\f[] The \f[B]add\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the sum, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]\-\f[] The \f[B]subtract\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns the difference, with a \f[I]scale\f[] equal to the max of the \f[I]scale\f[]s of \f[B]a\f[] and \f[B]b\f[]. .RS .RE .TP .B \f[B]<<\f[] The \f[B]left shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]>>\f[] The \f[B]right shift\f[] operator takes two expressions, \f[B]a\f[] and \f[B]b\f[], and returns a copy of the value of \f[B]a\f[] with its decimal point moved \f[B]b\f[] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[]) and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[] \f[B]<<=\f[] \f[B]>>=\f[] \f[B]+=\f[] \f[B]\-=\f[] \f[B]*=\f[] \f[B]/=\f[] \f[B]%=\f[] \f[B]^=\f[] \f[B]\@=\f[] The \f[B]assignment\f[] operators take two expressions, \f[B]a\f[] and \f[B]b\f[] where \f[B]a\f[] is a named expression (see the \f[I]Named Expressions\f[] subsection). .RS .PP For \f[B]=\f[], \f[B]b\f[] is copied and the result is assigned to \f[B]a\f[]. For all others, \f[B]a\f[] and \f[B]b\f[] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[]. .PP The \f[B]assignment\f[] operators that correspond to operators that are extensions are themselves \f[B]non\-portable extensions\f[]. .RE .TP .B \f[B]==\f[] \f[B]<=\f[] \f[B]>=\f[] \f[B]!=\f[] \f[B]<\f[] \f[B]>\f[] The \f[B]relational\f[] operators compare two expressions, \f[B]a\f[] and \f[B]b\f[], and if the relation holds, according to C language semantics, the result is \f[B]1\f[]. Otherwise, it is \f[B]0\f[]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[] operators, which means that \f[B]a=b>c\f[] is interpreted as \f[B](a=b)>c\f[]. .PP Also, unlike the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) requires, these operators can appear anywhere any other expressions can be used. This allowance is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]&&\f[] The \f[B]boolean and\f[] operator takes two expressions and returns \f[B]1\f[] if both expressions are non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]||\f[] The \f[B]boolean or\f[] operator takes two expressions and returns \f[B]1\f[] if one of the expressions is non\-zero, \f[B]0\f[] otherwise. .RS .PP This is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[] .IP " 2." 4 \f[B]{\f[] \f[B]S\f[] \f[B];\f[] ... \f[B];\f[] \f[B]S\f[] \f[B]}\f[] .IP " 3." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 4." 4 \f[B]if\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] \f[B]else\f[] \f[B]S\f[] .IP " 5." 4 \f[B]while\f[] \f[B](\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 6." 4 \f[B]for\f[] \f[B](\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B];\f[] \f[B]E\f[] \f[B])\f[] \f[B]S\f[] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[] .IP " 9." 4 \f[B]continue\f[] .IP "10." 4 \f[B]quit\f[] .IP "11." 4 \f[B]halt\f[] .IP "12." 4 \f[B]limits\f[] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[] \f[B]E\f[] \f[B],\f[] ... \f[B],\f[] \f[B]E\f[] .IP "15." 4 \f[B]I()\f[], \f[B]I(E)\f[], \f[B]I(E, E)\f[], and so on, where \f[B]I\f[] is an identifier for a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). The \f[B]E\f[] argument(s) may also be arrays of the form \f[B]I[]\f[], which will automatically be turned into array references (see the \f[I]Array References\f[] subsection of the \f[B]FUNCTIONS\f[] section) if the corresponding parameter in the function definition is an array reference. .PP Numbers 4, 9, 11, 12, 14, and 15 are \f[B]non\-portable extensions\f[]. .PP Also, as a \f[B]non\-portable extension\f[], any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant \f[B]1\f[]. .PP The \f[B]break\f[] statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. .PP The \f[B]continue\f[] statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. .PP The \f[B]if\f[] \f[B]else\f[] statement does the same thing as in C. .PP The \f[B]quit\f[] statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile\-time command). .PP The \f[B]halt\f[] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[] if it is on a branch of an \f[B]if\f[] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[] statement in that it is a compile\-time command. .PP An expression by itself is evaluated and printed, followed by a newline. .PP Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]\-s\f[] or \f[B]\-w\f[] command\-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .SS Print Statement .PP The "expressions" in a \f[B]print\f[] statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: .PP .TS tab(@); l l. T{ \f[B]\\a\f[] T}@T{ \f[B]\\a\f[] T} T{ \f[B]\\b\f[] T}@T{ \f[B]\\b\f[] T} T{ \f[B]\\\\\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\e\f[] T}@T{ \f[B]\\\f[] T} T{ \f[B]\\f\f[] T}@T{ \f[B]\\f\f[] T} T{ \f[B]\\n\f[] T}@T{ \f[B]\\n\f[] T} T{ \f[B]\\q\f[] T}@T{ \f[B]"\f[] T} T{ \f[B]\\r\f[] T}@T{ \f[B]\\r\f[] T} T{ \f[B]\\t\f[] T}@T{ \f[B]\\t\f[] T} .TE .PP Any other character following a backslash causes the backslash and character to be printed as\-is. .PP Any non\-string expression in a print statement shall be assigned to \f[B]last\f[], like any other expression that is printed. .SS Order of Evaluation .PP All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that \f[B]i\f[] is equal to \f[B]0\f[], in the expression .IP .nf \f[C] a[i++]\ =\ i++ \f[] .fi .PP the first (or 0th) element of \f[B]a\f[] is set to \f[B]1\f[], and \f[B]i\f[] is equal to \f[B]2\f[] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[] is equal to \f[B]0\f[], this means that in the expression .IP .nf \f[C] x(i++,\ i++) \f[] .fi .PP the first argument passed to \f[B]x()\f[] is \f[B]0\f[], and the second argument is \f[B]1\f[], while \f[B]i\f[] is equal to \f[B]2\f[] before the function starts executing. .SH FUNCTIONS .PP Function definitions are as follows: .IP .nf \f[C] define\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return(E) } \f[] .fi .PP Any \f[B]I\f[] in the parameter list or \f[B]auto\f[] list may be replaced with \f[B]I[]\f[] to make a parameter or \f[B]auto\f[] var an array, and any \f[B]I\f[] in the parameter list may be replaced with \f[B]*I[]\f[] to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just \f[B]I[]\f[] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non\-portable extension\f[], the opening brace of a \f[B]define\f[] statement may appear on the next line. .PP As a \f[B]non\-portable extension\f[], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[] .IP "2." 3 \f[B]return\f[] \f[B](\f[] \f[B])\f[] .IP "3." 3 \f[B]return\f[] \f[B]E\f[] .PP The first two, or not specifying a \f[B]return\f[] statement, is equivalent to \f[B]return (0)\f[], unless the function is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[] functions, defined as follows: .IP .nf \f[C] define\ void\ I(I,...,I){ \ \ \ \ auto\ I,...,I \ \ \ \ S;...;S \ \ \ \ return } \f[] .fi .PP They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. .PP Void functions can only use the first two \f[B]return\f[] statements listed above. They can also omit the return statement entirely. .PP The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[]. The word "void" is only treated specially right after the \f[B]define\f[] keyword. .PP This is a \f[B]non\-portable extension\f[]. .SS Array References .PP For any array in the parameter list, if the array is declared in the form .IP .nf \f[C] *I[] \f[] .fi .PP it is a \f[B]reference\f[]. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. .PP Other than this, all function arguments are passed by value. .PP This is a \f[B]non\-portable extension\f[]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[] subsection below), are available when the \f[B]\-l\f[] or \f[B]\-\-mathlib\f[] command\-line flags are given, except that the extended math library is not available when the \f[B]\-s\f[] option, the \f[B]\-w\f[] option, or equivalents are given. .SS Standard Library .PP The standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) defines the following functions for the math library: .TP .B \f[B]s(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]c(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l(x)\f[] Returns the natural logarithm of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]e(x)\f[] Returns the mathematical constant \f[B]e\f[] raised to the power of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]j(x, n)\f[] Returns the bessel integer order \f[B]n\f[] (truncated) of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[] loaded when the \f[B]\-s\f[]/\f[B]\-\-standard\f[] or \f[B]\-w\f[]/\f[B]\-\-warn\f[] options are given since they are not part of the library defined by the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html). .PP The extended library is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p(x, y)\f[] Calculates \f[B]x\f[] to the power of \f[B]y\f[], even if \f[B]y\f[] is not an integer, and returns the result to the current \f[B]scale\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round half away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .RS .RE .TP .B \f[B]ceil(x, p)\f[] Returns \f[B]x\f[] rounded to \f[B]p\f[] decimal places according to the rounding mode round away from \f[B]0\f[] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .RS .RE .TP .B \f[B]f(x)\f[] Returns the factorial of the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]perm(n, k)\f[] Returns the permutation of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]comb(n, k)\f[] Returns the combination of the truncated absolute value of \f[B]n\f[] of the truncated absolute value of \f[B]k\f[], if \f[B]k <= n\f[]. If not, it returns \f[B]0\f[]. .RS .RE .TP .B \f[B]l2(x)\f[] Returns the logarithm base \f[B]2\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]l10(x)\f[] Returns the logarithm base \f[B]10\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]log(x, b)\f[] Returns the logarithm base \f[B]b\f[] of \f[B]x\f[]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cbrt(x)\f[] Returns the cube root of \f[B]x\f[]. .RS .RE .TP .B \f[B]root(x, n)\f[] Calculates the truncated value of \f[B]n\f[], \f[B]r\f[], and returns the \f[B]r\f[]th root of \f[B]x\f[] to the current \f[B]scale\f[]. .RS .PP If \f[B]r\f[] is \f[B]0\f[] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[] is even and \f[B]x\f[] is negative. .RE .TP .B \f[B]pi(p)\f[] Returns \f[B]pi\f[] to \f[B]p\f[] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]t(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]a2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]sin(x)\f[] Returns the sine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]cos(x)\f[] Returns the cosine of \f[B]x\f[], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]tan(x)\f[] Returns the tangent of \f[B]x\f[], which is assumed to be in radians. .RS .PP If \f[B]x\f[] is equal to \f[B]1\f[] or \f[B]\-1\f[], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). .PP This is an alias of \f[B]t(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan(x)\f[] Returns the arctangent of \f[B]x\f[], in radians. .RS .PP This is an alias of \f[B]a(x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]atan2(y, x)\f[] Returns the arctangent of \f[B]y/x\f[], in radians. If both \f[B]y\f[] and \f[B]x\f[] are equal to \f[B]0\f[], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[] section). Otherwise, if \f[B]x\f[] is greater than \f[B]0\f[], it returns \f[B]a(y/x)\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is greater than or equal to \f[B]0\f[], it returns \f[B]a(y/x)+pi\f[]. If \f[B]x\f[] is less than \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]a(y/x)\-pi\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is greater than \f[B]0\f[], it returns \f[B]pi/2\f[]. If \f[B]x\f[] is equal to \f[B]0\f[], and \f[B]y\f[] is less than \f[B]0\f[], it returns \f[B]\-pi/2\f[]. .RS .PP This function is the same as the \f[B]atan2()\f[] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]r2d(x)\f[] Converts \f[B]x\f[] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]d2r(x)\f[] Converts \f[B]x\f[] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[] subsection below). .RE .TP .B \f[B]frand(p)\f[] Generates a pseudo\-random number between \f[B]0\f[] (inclusive) and \f[B]1\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]. If \f[B]p\f[] is \f[B]0\f[], then \f[B]0\f[] is returned, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .RE .TP .B \f[B]ifrand(i, p)\f[] Generates a pseudo\-random number that is between \f[B]0\f[] (inclusive) and the truncated absolute value of \f[B]i\f[] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[]. If the absolute value of \f[B]i\f[] is greater than or equal to \f[B]2\f[], and \f[B]p\f[] is not \f[B]0\f[], then calling this function will change the value of \f[B]seed\f[]; otherwise, \f[B]0\f[] is returned and \f[B]seed\f[] is not changed. .RS .RE .TP .B \f[B]srand(x)\f[] Returns \f[B]x\f[] with its sign flipped with probability \f[B]0.5\f[]. In other words, it randomizes the sign of \f[B]x\f[]. .RS .RE .TP .B \f[B]brand()\f[] Returns a random boolean value (either \f[B]0\f[] or \f[B]1\f[]). .RS .RE .TP .B \f[B]ubytes(x)\f[] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[]. .RS .RE .TP .B \f[B]sbytes(x)\f[] Returns the numbers of signed, two\[aq]s\-complement integer bytes required to hold the truncated value of \f[B]x\f[]. .RS .RE .TP .B \f[B]hex(x)\f[] Outputs the hexadecimal (base \f[B]16\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary(x)\f[] Outputs the binary (base \f[B]2\f[]) representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output(x, b)\f[] Outputs the base \f[B]b\f[] representation of \f[B]x\f[]. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uintn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]intn(x, n)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]n\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]n\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int8(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]1\f[] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]1\f[] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int16(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]2\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]2\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int32(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]4\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]4\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]uint64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as an unsigned integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer, is negative, or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]int64(x)\f[] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[] as a signed, two\[aq]s\-complement integer in \f[B]8\f[] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[] is not an integer or cannot fit into \f[B]8\f[] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]hex_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in hexadecimal using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]binary_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in binary using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_uint(x, n)\f[] Outputs the representation of the truncated absolute value of \f[B]x\f[] as an unsigned integer in the current \f[B]obase\f[] (see the \f[B]SYNTAX\f[] section) using \f[B]n\f[] bytes. Not all of the value will be output if \f[B]n\f[] is too small. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .TP .B \f[B]output_byte(x, i)\f[] Outputs byte \f[B]i\f[] of the truncated absolute value of \f[B]x\f[], where \f[B]0\f[] is the least significant byte and \f[B]number_of_bytes \- 1\f[] is the most significant byte. .RS .PP This is a \f[B]void\f[] function (see the \f[I]Void Functions\f[] subsection of the \f[B]FUNCTIONS\f[] section). .RE .SS Transcendental Functions .PP All transcendental functions can return slightly inaccurate results (up to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place)). This is unavoidable, and this article (https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT) explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. .PP Because of the possible inaccuracy, I recommend that users call those functions with the precision (\f[B]scale\f[]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[] required, users can double the precision (\f[B]scale\f[]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[] .IP \[bu] 2 \f[B]c(x)\f[] .IP \[bu] 2 \f[B]a(x)\f[] .IP \[bu] 2 \f[B]l(x)\f[] .IP \[bu] 2 \f[B]e(x)\f[] .IP \[bu] 2 \f[B]j(x, n)\f[] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[] .IP \[bu] 2 \f[B]l10(x)\f[] .IP \[bu] 2 \f[B]log(x, b)\f[] .IP \[bu] 2 \f[B]pi(p)\f[] .IP \[bu] 2 \f[B]t(x)\f[] .IP \[bu] 2 \f[B]a2(y, x)\f[] .IP \[bu] 2 \f[B]sin(x)\f[] .IP \[bu] 2 \f[B]cos(x)\f[] .IP \[bu] 2 \f[B]tan(x)\f[] .IP \[bu] 2 \f[B]atan(x)\f[] .IP \[bu] 2 \f[B]atan2(y, x)\f[] .IP \[bu] 2 \f[B]r2d(x)\f[] .IP \[bu] 2 \f[B]d2r(x)\f[] .SH RESET .PP When bc(1) encounters an error or a signal that it has a non\-default handler for, it resets. This means that several things happen. .PP First, any functions that are executing are stopped and popped off the 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 functions returned) is skipped. .PP Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .PP Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This bc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[]. .PP The actual values of \f[B]BC_LONG_BIT\f[] and \f[B]BC_BASE_DIGS\f[] can be queried with the \f[B]limits\f[] statement. .PP In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bc(1): .TP .B \f[B]BC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]BC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]BC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]BC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]BC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]BC_BASE_MAX\f[] The maximum output base. Set at \f[B]BC_BASE_POW\f[]. .RS .RE .TP .B \f[B]BC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]BC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]rand()\f[] operand. Set at \f[B]2^BC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP The actual values can be queried with the \f[B]limits\f[] statement. .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP bc(1) recognizes the following environment variables: .TP .B \f[B]POSIXLY_CORRECT\f[] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]\-s\f[] option was given. .RS .RE .TP .B \f[B]BC_ENV_ARGS\f[] This is another way to give command\-line arguments to bc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]BC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. .RS .PP The code that parses \f[B]BC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some bc file.bc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "bc" file.bc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]BC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]BC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), bc(1) will output lines to that length, including the backslash (\f[B]\\\f[]). The default line length is \f[B]70\f[]. -.RS -.RE -.TP -.B \f[B]BC_EXPR_EXIT\f[] -If this variable exists (no matter the contents), bc(1) will exit -immediately after executing expressions and files given by the -\f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any -equivalents). .RS .RE .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]<<\f[]), and right shift (\f[B]>>\f[]) operators and their corresponding assignment operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the \f[I]Named Expressions\f[] subsection of the \f[B]SYNTAX\f[] section), giving an invalid \f[B]auto\f[] list, having a duplicate \f[B]auto\f[]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]\-s\f[] or any equivalents were given. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a \f[B]void\f[] function call as a value in an expression. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP Fatal errors include memory allocation errors, I/O errors, failing to open files, attempting to use files that do not have only ASCII characters (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command\-line options. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[], no matter what mode bc(1) is in. .PP The other statuses will only be returned when bc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since bc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP These exit statuses allow bc(1) to be used in shell scripting with error checking, and its normal behavior can be forced by using the \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Per the standard (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), bc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, bc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, bc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause bc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP bc(1) supports interactive command\-line editing. If bc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This bc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGES\f[]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]\-efghiqsvVw\f[], all long options, and the extensions noted above are extensions to that specification. .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/bc/P.1.md =================================================================== --- head/contrib/bc/manuals/bc/P.1.md (revision 363809) +++ head/contrib/bc/manuals/bc/P.1.md (revision 363810) @@ -1,1691 +1,1685 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment 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, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/bc.1.md.in =================================================================== --- head/contrib/bc/manuals/bc.1.md.in (revision 363809) +++ head/contrib/bc/manuals/bc.1.md.in (revision 363810) @@ -1,1814 +1,1808 @@ # NAME bc - arbitrary-precision arithmetic language and calculator # SYNOPSIS **bc** [**-ghilPqsvVw**] [**--global-stacks**] [**--help**] [**--interactive**] [**--mathlib**] [**--no-prompt**] [**--quiet**] [**--standard**] [**--warn**] [**--version**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION bc(1) is an interactive processor for a language first standardized in 1991 by POSIX. (The current standard is [here][1].) The language provides unlimited precision decimal arithmetic and is somewhat C-like, but there are differences. Such differences will be noted in this document. After parsing and handling options, this bc(1) reads any files given on the command line and executes them before reading from **stdin**. {{ A N P NP }} This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). It also has many extensions and extra features beyond other implementations. {{ end }} {{ E EN EP ENP }} This bc(1) is a drop-in replacement for *any* bc(1), including (and especially) the GNU bc(1). {{ end }} # OPTIONS The following are the options that bc(1) accepts. **-g**, **--global-stacks** {{ A H N P HN HP NP HNP }} : Turns the globals **ibase**, **obase**, **scale**, and **seed** into stacks. This has the effect that a copy of the current value of all four are pushed {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} Turns the globals **ibase**, **obase**, and **scale** into stacks. This has the effect that a copy of the current value of all three are pushed {{ end }} onto a stack for every function call, as well as popped when every function returns. This means that functions can assign to any and all of those globals without worrying that the change will affect other functions. Thus, a hypothetical function named **output(x,b)** that simply printed **x** in base **b** could be written like this: define void output(x, b) { obase=b x } instead of like this: define void output(x, b) { auto c c=obase obase=b x obase=c } This makes writing functions much easier. {{ A H N P HN HP NP HNP }} (**Note**: the function **output(x,b)** exists in the extended math library. See the **LIBRARY** section.) However, since using this flag means that functions cannot set **ibase**, **obase**, **scale**, or **seed** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} However, since using this flag means that functions cannot set **ibase**, **obase**, or **scale** globally, functions that are made to do so cannot work anymore. There are two possible use cases for that, and each has a solution. {{ end }} First, if a function is called on startup to turn bc(1) into a number converter, it is possible to replace that capability with various shell aliases. Examples: alias d2o="bc -e ibase=A -e obase=8" alias h2b="bc -e ibase=G -e obase=2" {{ A H N P HN HP NP HNP }} Second, if the purpose of a function is to set **ibase**, **obase**, **scale**, or **seed** globally for any other purpose, it could be split into one to four functions (based on how many globals it sets) and each of those functions could return the desired value for a global. For functions that set **seed**, the value assigned to **seed** is not propagated to parent functions. This means that the sequence of pseudo-random numbers that they see will not be the same sequence of pseudo-random numbers that any parent sees. This is only the case once **seed** has been set. If a function desires to not affect the sequence of pseudo-random numbers of its parents, but wants to use the same **seed**, it can use the following line: seed = seed {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} Second, if the purpose of a function is to set **ibase**, **obase**, or **scale** globally for any other purpose, it could be split into one to three functions (based on how many globals it sets) and each of those functions could return the desired value for a global. {{ end }} If the behavior of this option is desired for every run of bc(1), then users could make sure to define **BC_ENV_ARGS** and include this option (see the **ENVIRONMENT VARIABLES** section for more details). If **-s**, **-w**, or any equivalents are used, this option is ignored. This is a **non-portable extension**. **-h**, **--help** : Prints a usage message and quits. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-l**, **--mathlib** : Sets **scale** (see the **SYNTAX** section) to **20** and loads the included {{ A H N P HN HP NP HNP }} math library and the extended math library before running any code, including any expressions or files specified on the command line. To learn what is in the libraries, see the **LIBRARY** section. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} math library before running any code, including any expressions or files specified on the command line. To learn what is in the library, see the **LIBRARY** section. {{ end }} **-P**, **--no-prompt** {{ A E H N EH EN HN EHN }} : 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 in bc(1). Most of those users would want to put this option in **BC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). {{ end }} {{ P EP HP NP EHP ENP HNP EHNP }} : This option is a no-op. {{ end }} This is a **non-portable extension**. **-q**, **--quiet** -: Do not print copyright header. bc(1) will also suppress the header in - non-interactive mode. +: This option is for compatibility with the [GNU bc(1)][2]; it is a no-op. + Without this option, GNU bc(1) prints a copyright header. This bc(1) only + prints the copyright header if one or more of the **-v**, **-V**, or + **--version** options are given. - This is mostly for compatibility with the [GNU bc(1)][2]. - This is a **non-portable extension**. **-s**, **--standard** : Process exactly the language defined by the [standard][1] and error if any extensions are used. This is a **non-portable extension**. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. **-w**, **--warn** : Like **-s** and **--standard**, except that warnings (and not errors) are printed for non-standard extensions and execution continues normally. This is a **non-portable extension**. **-e** *expr*, **--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. - In other bc(1) implementations, this option causes the program to execute - the expressions and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. **-f** *file*, **--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. - In other bc(1) implementations, this option causes the program to execute - the files and then exit. This bc(1) does not, unless the - **BC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, bc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **bc >&-**, it will quit with an error. This is done so that bc(1) can report problems when **stdout** is redirected to a file. If there are scripts that depend on the behavior of other bc(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 other bc(1) implementations, this bc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **bc 2>&-**, it will quit with an error. This is done so that bc(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 bc(1) implementations, it is recommended that those scripts be changed to redirect **stderr** to **/dev/null**. # SYNTAX The syntax for bc(1) programs is mostly C-like, with some differences. This bc(1) follows the [POSIX standard][1], which is a much more thorough resource for the language this bc(1) accepts. This section is meant to be a summary and a listing of all the extensions to the standard. In the sections below, **E** means expression, **S** means statement, and **I** means identifier. Identifiers (**I**) start with a lowercase letter and can be followed by any number (up to **BC_NAME_MAX-1**) of lowercase letters (**a-z**), digits (**0-9**), and underscores (**\_**). The regex is **\[a-z\]\[a-z0-9\_\]\***. Identifiers with more than one character (letter) are a **non-portable extension**. **ibase** is a global variable determining how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **10**. If the **-s** (**--standard**) and **-w** (**--warn**) flags were not given on the command line, the max allowable value for **ibase** is **36**. Otherwise, it is **16**. The min allowable value for **ibase** is **2**. The max allowable value for **ibase** can be queried in bc(1) programs with the **maxibase()** built-in function. **obase** is a global variable determining how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **BC_BASE_MAX** and can be queried in bc(1) programs with the **maxobase()** built-in function. The {{ A H N P HN HP NP HNP }} 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**. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} min allowable value for **obase** is **2**. Values are output in the specified base. {{ end }} 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 global variable that sets the precision of any operations, with exceptions. **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** is **BC_SCALE_MAX** and can be queried in bc(1) programs with the **maxscale()** built-in function. bc(1) has both *global* variables and *local* variables. All *local* variables are local to the function; they are parameters or are introduced in the **auto** list of a function (see the **FUNCTIONS** section). If a variable is accessed which is not a parameter or in the **auto** list, it is assumed to be *global*. If a parent function has a *local* variable version of a variable that a child function considers *global*, the value of that *global* variable in the child function is the value of the variable in the parent function, not the value of the actual *global* variable. All of the above applies to arrays as well. The value of a statement that is an expression (i.e., any of the named expressions or operands) is printed unless the lowest precedence operator is an assignment operator *and* the expression is notsurrounded by parentheses. The value that is printed is also assigned to the special variable **last**. A single dot (**.**) may also be used as a synonym for **last**. These are **non-portable extensions**. Either semicolons or newlines may separate statements. ## Comments There are two kinds of comments: 1. Block comments are enclosed in **/\*** and **\*/**. 2. Line comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. ## Named Expressions The following are named expressions in bc(1): 1. Variables: **I** 2. Array Elements: **I[E]** 3. **ibase** 4. **obase** 5. **scale** {{ A H N P HN HP NP HNP }} 6. **seed** 7. **last** or a single dot (**.**) Numbers 6 and 7 are **non-portable extensions**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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 assigned to **seed** and 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. The exact value assigned to **seed** is not guaranteed to be returned if **seed** is queried again immediately. 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. The value of **seed** will change after any use of the **rand()** and **irand(E)** operands (see the *Operands* subsection below), except if the parameter passed to **irand(E)** is **0**, **1**, or negative. There is no limit to the length (number of significant decimal digits) or *scale* of the value that can be assigned to **seed**. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} 6. **last** or a single dot (**.**) Number 6 is a **non-portable extension**. {{ end }} Variables and arrays do not interfere; users can have arrays named the same as variables. This also applies to functions (see the **FUNCTIONS** section), so a user can have a variable, array, and function that all have the same name, and they will not shadow each other, whether inside of functions or not. Named expressions are required as the operand of **increment**/**decrement** operators and as the left side of **assignment** operators (see the *Operators* subsection). ## Operands The following are valid operands in bc(1): 1. Numbers (see the *Numbers* subsection below). 2. Array indices (**I[E]**). 3. **(E)**: The value of **E** (used to change precedence). 4. **sqrt(E)**: The square root of **E**. **E** must be non-negative. 5. **length(E)**: The number of significant decimal digits in **E**. 6. **length(I[])**: The number of elements in the array **I**. This is a **non-portable extension**. 7. **scale(E)**: The *scale* of **E**. 8. **abs(E)**: The absolute value of **E**. This is a **non-portable extension**. 9. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a non-**void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. 10. **read()**: Reads a line from **stdin** and uses that as an expression. The result of that expression is the result of the **read()** operand. This is a **non-portable extension**. 11. **maxibase()**: The max allowable **ibase**. This is a **non-portable extension**. 12. **maxobase()**: The max allowable **obase**. This is a **non-portable extension**. 13. **maxscale()**: The max allowable **scale**. This is a **non-portable extension**. {{ A H N P HN HP NP HNP }} 14. **rand()**: A pseudo-random integer between **0** (inclusive) and **BC_RAND_MAX** (inclusive). Using this operand will change the value of **seed**. This is a **non-portable extension**. 15. **irand(E)**: A pseudo-random integer between **0** (inclusive) and the value of **E** (exclusive). If **E** is negative or is a non-integer (**E**'s *scale* is not **0**), an error is raised, and bc(1) resets (see the **RESET** section) while **seed** remains unchanged. If **E** is larger than **BC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **BC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this operand is unbounded. Using this operand will change the value of **seed**, unless the value of **E** is **0** or **1**. In that case, **0** is returned, and **seed** is *not* changed. This is a **non-portable extension**. 16. **maxrand()**: The max integer returned by **rand()**. This is a **non-portable extension**. The integers generated by **rand()** and **irand(E)** are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. **Note**: The values returned by the pseudo-random number generator with **rand()** and **irand(E)** 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. {{ end }} ## Numbers Numbers are strings made up of digits, uppercase letters, and at most **1** period for a radix. Numbers can have up to **BC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **Z** alone always equals decimal **35**. {{ A H N P HN HP NP HNP }} In addition, bc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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**. Using scientific notation is an error or warning if the **-s** or **-w**, respectively, command-line options (or equivalents) are given. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bc(1) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. {{ end }} ## Operators The following arithmetic and logical operators can be used. They are listed in order of decreasing precedence. Operators in the same group have the same precedence. **++** **--** : Type: Prefix and Postfix Associativity: None Description: **increment**, **decrement** **-** **!** : Type: Prefix Associativity: None Description: **negation**, **boolean not** {{ A H N P HN HP NP HNP }} **\$** : Type: Postfix Associativity: None Description: **truncation** **\@** : Type: Binary Associativity: Right Description: **set precision** {{ end }} **\^** : Type: Binary Associativity: Right Description: **power** **\*** **/** **%** : Type: Binary Associativity: Left Description: **multiply**, **divide**, **modulus** **+** **-** : Type: Binary Associativity: Left Description: **add**, **subtract** {{ A H N P HN HP NP HNP }} **\<\<** **\>\>** : Type: Binary Associativity: Left Description: **shift left**, **shift right** **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} **=** **+=** **-=** **\*=** **/=** **%=** **\^=** {{ end }} : Type: Binary Associativity: Right Description: **assignment** **==** **\<=** **\>=** **!=** **\<** **\>** : Type: Binary Associativity: Left Description: **relational** **&&** : Type: Binary Associativity: Left Description: **boolean and** **||** : Type: Binary Associativity: Left Description: **boolean or** The operators will be described in more detail below. **++** **--** : The prefix and postfix **increment** and **decrement** operators behave exactly like they would in C. They require a named expression (see the *Named Expressions* subsection) as an operand. The prefix versions of these operators are more efficient; use them where possible. **-** : The **negation** operator returns **0** if a user attempts to negate any expression with the value **0**. Otherwise, a copy of the expression with its sign flipped is returned. **!** : The **boolean not** operator returns **1** if the expression is **0**, or **0** otherwise. This is a **non-portable extension**. {{ A H N P HN HP NP HNP }} **\$** : The **truncation** operator returns a copy of the given expression with all of its *scale* removed. This is a **non-portable extension**. **\@** : The **set precision** operator takes two expressions and returns a copy of the first with its *scale* equal to the value of the second expression. That could either mean that the number is returned without change (if the *scale* of the first expression matches the value of the second expression), extended (if it is less), or truncated (if it is more). The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. {{ end }} **\^** : The **power** operator (not the **exclusive or** operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The second expression must be an integer (no *scale*), and if it is negative, the first value must be non-zero. **\*** : The **multiply** operator takes two expressions, multiplies them, and returns the product. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** return the obvious values. **/** : The **divide** operator takes two expressions, divides them, and returns the quotient. The *scale* of the result shall be the value of **scale**. The second expression must be non-zero. **%** : The **modulus** operator takes two expressions, **a** and **b**, and evaluates them by 1) Computing **a/b** to current **scale** and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(scale+scale(b),scale(a))**. The second expression must be non-zero. **+** : The **add** operator takes two expressions, **a** and **b**, and returns the sum, with a *scale* equal to the max of the *scale*s of **a** and **b**. **-** : The **subtract** operator takes two expressions, **a** and **b**, and returns the difference, with a *scale* equal to the max of the *scale*s of **a** and **b**. {{ A H N P HN HP NP HNP }} **\<\<** : The **left shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the right. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. **\>\>** : The **right shift** operator takes two expressions, **a** and **b**, and returns a copy of the value of **a** with its decimal point moved **b** places to the left. The second expression must be an integer (no *scale*) and non-negative. This is a **non-portable extension**. {{ end }} {{ A H N P HN HP NP HNP }} **=** **\<\<=** **\>\>=** **+=** **-=** **\*=** **/=** **%=** **\^=** **\@=** {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} **=** **+=** **-=** **\*=** **/=** **%=** **\^=** {{ end }} : The **assignment** operators take two expressions, **a** and **b** where **a** is a named expression (see the *Named Expressions* subsection). For **=**, **b** is copied and the result is assigned to **a**. For all others, **a** and **b** are applied as operands to the corresponding arithmetic operator and the result is assigned to **a**. {{ A H N P HN HP NP HNP }} The **assignment** operators that correspond to operators that are extensions are themselves **non-portable extensions**. {{ end }} **==** **\<=** **\>=** **!=** **\<** **\>** : The **relational** operators compare two expressions, **a** and **b**, and if the relation holds, according to C language semantics, the result is **1**. Otherwise, it is **0**. Note that unlike in C, these operators have a lower precedence than the **assignment** operators, which means that **a=b\>c** is interpreted as **(a=b)\>c**. Also, unlike the [standard][1] requires, these operators can appear anywhere any other expressions can be used. This allowance is a **non-portable extension**. **&&** : The **boolean and** operator takes two expressions and returns **1** if both expressions are non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. **||** : The **boolean or** operator takes two expressions and returns **1** if one of the expressions is non-zero, **0** otherwise. This is *not* a short-circuit operator. This is a **non-portable extension**. ## Statements The following items are statements: 1. **E** 2. **{** **S** **;** ... **;** **S** **}** 3. **if** **(** **E** **)** **S** 4. **if** **(** **E** **)** **S** **else** **S** 5. **while** **(** **E** **)** **S** 6. **for** **(** **E** **;** **E** **;** **E** **)** **S** 7. An empty statement 8. **break** 9. **continue** 10. **quit** 11. **halt** 12. **limits** 13. A string of characters, enclosed in double quotes 14. **print** **E** **,** ... **,** **E** 15. **I()**, **I(E)**, **I(E, E)**, and so on, where **I** is an identifier for a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). The **E** argument(s) may also be arrays of the form **I[]**, which will automatically be turned into array references (see the *Array References* subsection of the **FUNCTIONS** section) if the corresponding parameter in the function definition is an array reference. Numbers 4, 9, 11, 12, 14, and 15 are **non-portable extensions**. Also, as a **non-portable extension**, any or all of the expressions in the header of a for loop may be omitted. If the condition (second expression) is omitted, it is assumed to be a constant **1**. The **break** statement causes a loop to stop iterating and resume execution immediately following a loop. This is only allowed in loops. The **continue** statement causes a loop iteration to stop early and returns to the start of the loop, including testing the loop condition. This is only allowed in loops. The **if** **else** statement does the same thing as in C. The **quit** statement causes bc(1) to quit, even if it is on a branch that will not be executed (it is a compile-time command). The **halt** statement causes bc(1) to quit, if it is executed. (Unlike **quit** if it is on a branch of an **if** statement that is not executed, bc(1) does not quit.) The **limits** statement prints the limits that this bc(1) is subject to. This is like the **quit** statement in that it is a compile-time command. An expression by itself is evaluated and printed, followed by a newline. {{ A H N P HN HP NP HNP }} Both scientific notation and engineering notation are available for printing the results of expressions. Scientific notation is activated by assigning **0** to **obase**, and engineering notation is activated by assigning **1** to **obase**. To deactivate them, just assign a different value to **obase**. Scientific notation and engineering notation are disabled if bc(1) is run with either the **-s** or **-w** command-line options (or equivalents). Printing numbers in scientific notation and/or engineering notation is a **non-portable extension**. {{ end }} ## Print Statement The "expressions" in a **print** statement may also be strings. If they are, there are backslash escape sequences that are interpreted specially. What those sequences are, and what they cause to be printed, are shown below: -------- ------- **\\a** **\\a** **\\b** **\\b** **\\\\** **\\** **\\e** **\\** **\\f** **\\f** **\\n** **\\n** **\\q** **"** **\\r** **\\r** **\\t** **\\t** -------- ------- Any other character following a backslash causes the backslash and character to be printed as-is. Any non-string expression in a print statement shall be assigned to **last**, like any other expression that is printed. ## Order of Evaluation All expressions in a statment are evaluated left to right, except as necessary to maintain order of operations. This means, for example, assuming that **i** is equal to **0**, in the expression a[i++] = i++ the first (or 0th) element of **a** is set to **1**, and **i** is equal to **2** at the end of the expression. This includes function arguments. Thus, assuming **i** is equal to **0**, this means that in the expression x(i++, i++) the first argument passed to **x()** is **0**, and the second argument is **1**, while **i** is equal to **2** before the function starts executing. # FUNCTIONS Function definitions are as follows: ``` define I(I,...,I){ auto I,...,I S;...;S return(E) } ``` Any **I** in the parameter list or **auto** list may be replaced with **I[]** to make a parameter or **auto** var an array, and any **I** in the parameter list may be replaced with **\*I[]** to make a parameter an array reference. Callers of functions that take array references should not put an asterisk in the call; they must be called with just **I[]** like normal array parameters and will be automatically converted into references. As a **non-portable extension**, the opening brace of a **define** statement may appear on the next line. As a **non-portable extension**, the return statement may also be in one of the following forms: 1. **return** 2. **return** **(** **)** 3. **return** **E** The first two, or not specifying a **return** statement, is equivalent to **return (0)**, unless the function is a **void** function (see the *Void Functions* subsection below). ## Void Functions Functions can also be **void** functions, defined as follows: ``` define void I(I,...,I){ auto I,...,I S;...;S return } ``` They can only be used as standalone expressions, where such an expression would be printed alone, except in a print statement. Void functions can only use the first two **return** statements listed above. They can also omit the return statement entirely. The word "void" is not treated as a keyword; it is still possible to have variables, arrays, and functions named **void**. The word "void" is only treated specially right after the **define** keyword. This is a **non-portable extension**. ## Array References For any array in the parameter list, if the array is declared in the form ``` *I[] ``` it is a **reference**. Any changes to the array in the function are reflected, when the function returns, to the array that was passed in. Other than this, all function arguments are passed by value. This is a **non-portable extension**. # LIBRARY {{ A H N P HN HP NP HNP }} All of the functions below, including the functions in the extended math library (see the *Extended Library* subsection below), are available when the **-l** or **--mathlib** command-line flags are given, except that the extended math library is not available when the **-s** option, the **-w** option, or equivalents are given. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} All of the functions below are available when the **-l** or **--mathlib** command-line flags are given. {{ end }} ## Standard Library The [standard][1] defines the following functions for the math library: **s(x)** : Returns the sine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **c(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a(x)** : Returns the arctangent of **x**, in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **l(x)** : Returns the natural logarithm of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **e(x)** : Returns the mathematical constant **e** raised to the power of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **j(x, n)** : Returns the bessel integer order **n** (truncated) of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). {{ A H N P HN HP NP HNP }} ## Extended Library The extended library is *not* loaded when the **-s**/**--standard** or **-w**/**--warn** options are given since they are not part of the library defined by the [standard][1]. The extended library is a **non-portable extension**. **p(x, y)** : Calculates **x** to the power of **y**, even if **y** is not an integer, and returns the result to the current **scale**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round half away from **0**][3]. **ceil(x, p)** : Returns **x** rounded to **p** decimal places according to the rounding mode [round away from **0**][6]. **f(x)** : Returns the factorial of the truncated absolute value of **x**. **perm(n, k)** : Returns the permutation of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **comb(n, k)** : Returns the combination of the truncated absolute value of **n** of the truncated absolute value of **k**, if **k \<= n**. If not, it returns **0**. **l2(x)** : Returns the logarithm base **2** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **l10(x)** : Returns the logarithm base **10** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **log(x, b)** : Returns the logarithm base **b** of **x**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cbrt(x)** : Returns the cube root of **x**. **root(x, n)** : Calculates the truncated value of **n**, **r**, and returns the **r**th root of **x** to the current **scale**. If **r** is **0** or negative, this raises an error and causes bc(1) to reset (see the **RESET** section). It also raises an error and causes bc(1) to reset if **r** is even and **x** is negative. **pi(p)** : Returns **pi** to **p** decimal places. This is a transcendental function (see the *Transcendental Functions* subsection below). **t(x)** : Returns the tangent of **x**, which is assumed to be in radians. This is a transcendental function (see the *Transcendental Functions* subsection below). **a2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is a transcendental function (see the *Transcendental Functions* subsection below). **sin(x)** : Returns the sine of **x**, which is assumed to be in radians. This is an alias of **s(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **cos(x)** : Returns the cosine of **x**, which is assumed to be in radians. This is an alias of **c(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **tan(x)** : Returns the tangent of **x**, which is assumed to be in radians. If **x** is equal to **1** or **-1**, this raises an error and causes bc(1) to reset (see the **RESET** section). This is an alias of **t(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan(x)** : Returns the arctangent of **x**, in radians. This is an alias of **a(x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **atan2(y, x)** : Returns the arctangent of **y/x**, in radians. If both **y** and **x** are equal to **0**, it raises an error and causes bc(1) to reset (see the **RESET** section). Otherwise, if **x** is greater than **0**, it returns **a(y/x)**. If **x** is less than **0**, and **y** is greater than or equal to **0**, it returns **a(y/x)+pi**. If **x** is less than **0**, and **y** is less than **0**, it returns **a(y/x)-pi**. If **x** is equal to **0**, and **y** is greater than **0**, it returns **pi/2**. If **x** is equal to **0**, and **y** is less than **0**, it returns **-pi/2**. This function is the same as the **atan2()** function in many programming languages. This is an alias of **a2(y, x)**. This is a transcendental function (see the *Transcendental Functions* subsection below). **r2d(x)** : Converts **x** from radians to degrees and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **d2r(x)** : Converts **x** from degrees to radians and returns the result. This is a transcendental function (see the *Transcendental Functions* subsection below). **frand(p)** : Generates a pseudo-random number between **0** (inclusive) and **1** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If **p** is not **0**, then calling this function will change the value of **seed**. If **p** is **0**, then **0** is returned, and **seed** is *not* changed. **ifrand(i, p)** : Generates a pseudo-random number that is between **0** (inclusive) and the truncated absolute value of **i** (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of **p**. If the absolute value of **i** is greater than or equal to **2**, and **p** is not **0**, then calling this function will change the value of **seed**; otherwise, **0** is returned and **seed** is not changed. **srand(x)** : Returns **x** with its sign flipped with probability **0.5**. In other words, it randomizes the sign of **x**. **brand()** : Returns a random boolean value (either **0** or **1**). **ubytes(x)** : Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of **x**. **sbytes(x)** : Returns the numbers of signed, two's-complement integer bytes required to hold the truncated value of **x**. **hex(x)** : Outputs the hexadecimal (base **16**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary(x)** : Outputs the binary (base **2**) representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output(x, b)** : Outputs the base **b** representation of **x**. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer or is negative, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in as few power of two bytes as possible. Both outputs are split into bytes separated by spaces. If **x** is not an integer, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uintn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **intn(x, n)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **n** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **n** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int8(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **1** byte. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **1** byte, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int16(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **2** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **2** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int32(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **4** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **4** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **uint64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as an unsigned integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer, is negative, or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **int64(x)** : Outputs the representation, in binary and hexadecimal, of **x** as a signed, two's-complement integer in **8** bytes. Both outputs are split into bytes separated by spaces. If **x** is not an integer or cannot fit into **8** bytes, an error message is printed instead, but bc(1) is not reset (see the **RESET** section). This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **hex_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in hexadecimal using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **binary_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in binary using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_uint(x, n)** : Outputs the representation of the truncated absolute value of **x** as an unsigned integer in the current **obase** (see the **SYNTAX** section) using **n** bytes. Not all of the value will be output if **n** is too small. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). **output_byte(x, i)** : Outputs byte **i** of the truncated absolute value of **x**, where **0** is the least significant byte and **number_of_bytes - 1** is the most significant byte. This is a **void** function (see the *Void Functions* subsection of the **FUNCTIONS** section). {{ end }} ## Transcendental Functions All transcendental functions can return slightly inaccurate results (up to 1 [ULP][4]). This is unavoidable, and [this article][5] explains why it is impossible and unnecessary to calculate exact results for the transcendental functions. Because of the possible inaccuracy, I recommend that users call those functions with the precision (**scale**) set to at least 1 higher than is necessary. If exact results are *absolutely* required, users can double the precision (**scale**) and then truncate. The transcendental functions in the standard math library are: * **s(x)** * **c(x)** * **a(x)** * **l(x)** * **e(x)** * **j(x, n)** {{ A H N P HN HP NP HNP }} The transcendental functions in the extended math library are: * **l2(x)** * **l10(x)** * **log(x, b)** * **pi(p)** * **t(x)** * **a2(y, x)** * **sin(x)** * **cos(x)** * **tan(x)** * **atan(x)** * **atan2(y, x)** * **r2d(x)** * **d2r(x)** {{ end }} # RESET When bc(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 functions that are executing are stopped and popped off the 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 functions returned) is skipped. Thus, when bc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. Note that this reset behavior is different from the GNU bc(1), which attempts to start executing the statement right after the one that caused an error. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. This bc(1) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. The actual values of **BC_LONG_BIT** and **BC_BASE_DIGS** can be queried with the **limits** statement. In addition, this bc(1) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bc(1): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_STRING_MAX** : The maximum length of strings. Set at **BC_OVERFLOW_MAX-1**. **BC_NAME_MAX** : The maximum length of identifiers. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. {{ A H N P HN HP NP HNP }} **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **rand()** operand. Set at **2\^BC_LONG_BIT-1**. {{ end }} Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. Number of vars : The maximum number of vars/arrays. Set at **SIZE_MAX-1**. The actual values can be queried with the **limits** statement. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES bc(1) recognizes the following environment variables: **POSIXLY_CORRECT** : If this variable exists (no matter the contents), bc(1) behaves as if the **-s** option was given. **BC_ENV_ARGS** : This is another way to give command-line arguments to bc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **BC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time bc(1) runs. The code that parses **BC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some bc file.bc"** will be correctly parsed, but the string **"/home/gavin/some \"bc\" file.bc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **BC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **BC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), bc(1) will output lines to that length, including the backslash (**\\**). The default line length is **70**. - -**BC_EXPR_EXIT** - -: If this variable exists (no matter the contents), bc(1) will exit - immediately after executing expressions and files given by the **-e** and/or - **-f** command-line options (and any equivalents). # EXIT STATUS bc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for expected errors, since math errors will happen in the process of normal execution. {{ A H N P HN HP NP HNP }} 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, 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 (**\<\<**), and right shift (**\>\>**) operators and their corresponding assignment operators. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} Math errors include divide by **0**, taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator and the corresponding assignment operator. {{ end }} **2** : A parse error occurred. Parse errors include unexpected **EOF**, using an invalid character, failing to find the end of a string or comment, using a token where it is invalid, giving an invalid expression, giving an invalid print statement, giving an invalid function definition, attempting to assign to an expression that is not a named expression (see the *Named Expressions* subsection of the **SYNTAX** section), giving an invalid **auto** list, having a duplicate **auto**/function parameter, failing to find the end of a code block, attempting to return a value from a **void** function, attempting to use a variable as a reference, and using any extensions when the option **-s** or any equivalents were given. **3** : A runtime error occurred. Runtime errors include assigning an invalid number to **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, passing the wrong number of arguments to functions, attempting to call an undefined function, and attempting to use a **void** function call as a value in an expression. **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 (bc(1) only accepts ASCII characters), attempting to open a directory as a file, and giving invalid command-line options. The exit status **4** is special; when a fatal error occurs, bc(1) always exits and returns **4**, no matter what mode bc(1) is in. The other statuses will only be returned when bc(1) is not in interactive mode (see the **INTERACTIVE MODE** section), since bc(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 bc(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 Per the [standard][1], bc(1) has an interactive mode and a non-interactive mode. Interactive mode is 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 cases. In interactive mode, bc(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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, bc(1) turns on "TTY mode." {{ A E N P EN EP NP ENP }} TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. {{ end }} {{ A E H N EH EN HN EHN }} The prompt is enabled in TTY mode. {{ end }} TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause bc(1) to stop execution of the current input. If bc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If bc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If bc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to bc(1) as it is executing a file, it can seem as though bc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with bc(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. **SIGTERM** and **SIGQUIT** cause bc(1) to clean up and exit, and it uses the {{ A E N P EN EP NP ENP }} default handler for all other signals. The one exception is **SIGHUP**; in that case, when bc(1) is in TTY mode, a **SIGHUP** will cause bc(1) to clean up and exit. {{ end }} {{ H EH HN HP EHN EHP HNP EHNP }} default handler for all other signals. {{ end }} {{ A E N P EN EP NP ENP }} # COMMAND LINE HISTORY bc(1) supports interactive command-line editing. If bc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. {{ end }} {{ A E H P EH EP HP EHP }} # LOCALES This bc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGES**. {{ end }} # SEE ALSO dc(1) # STANDARDS bc(1) is compliant with the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. The flags **-efghiqsvVw**, all long options, and the extensions noted above are extensions to that specification. Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. {{ A E H P EH EP HP EHP }} This bc(1) supports error messages for different locales, and thus, it supports **LC_MESSAGES**. {{ end }} # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero [4]: https://en.wikipedia.org/wiki/Unit_in_the_last_place [5]: https://people.eecs.berkeley.edu/~wkahan/LOG10HAF.TXT [6]: https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero Index: head/contrib/bc/manuals/dc/A.1 =================================================================== --- head/contrib/bc/manuals/dc/A.1 (revision 363809) +++ head/contrib/bc/manuals/dc/A.1 (revision 363810) @@ -1,1406 +1,1407 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/A.1.md =================================================================== --- head/contrib/bc/manuals/dc/A.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/A.1.md (revision 363810) @@ -1,1194 +1,1194 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/E.1 =================================================================== --- head/contrib/bc/manuals/dc/E.1 (revision 363809) +++ head/contrib/bc/manuals/dc/E.1 (revision 363810) @@ -1,1202 +1,1203 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/E.1.md =================================================================== --- head/contrib/bc/manuals/dc/E.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/E.1.md (revision 363810) @@ -1,1030 +1,1030 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/EH.1 =================================================================== --- head/contrib/bc/manuals/dc/EH.1 (revision 363809) +++ head/contrib/bc/manuals/dc/EH.1 (revision 363810) @@ -1,1187 +1,1188 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/EH.1.md =================================================================== --- head/contrib/bc/manuals/dc/EH.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/EH.1.md (revision 363810) @@ -1,1017 +1,1017 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/EHN.1 =================================================================== --- head/contrib/bc/manuals/dc/EHN.1 (revision 363809) +++ head/contrib/bc/manuals/dc/EHN.1 (revision 363810) @@ -1,1183 +1,1184 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/EHN.1.md =================================================================== --- head/contrib/bc/manuals/dc/EHN.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/EHN.1.md (revision 363810) @@ -1,1012 +1,1012 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/EHNP.1 =================================================================== --- head/contrib/bc/manuals/dc/EHNP.1 (revision 363809) +++ head/contrib/bc/manuals/dc/EHNP.1 (revision 363810) @@ -1,1176 +1,1177 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/EHNP.1.md =================================================================== --- head/contrib/bc/manuals/dc/EHNP.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/EHNP.1.md (revision 363810) @@ -1,1007 +1,1007 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/EHP.1 =================================================================== --- head/contrib/bc/manuals/dc/EHP.1 (revision 363809) +++ head/contrib/bc/manuals/dc/EHP.1 (revision 363810) @@ -1,1180 +1,1181 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/EHP.1.md =================================================================== --- head/contrib/bc/manuals/dc/EHP.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/EHP.1.md (revision 363810) @@ -1,1012 +1,1012 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/EN.1 =================================================================== --- head/contrib/bc/manuals/dc/EN.1 (revision 363809) +++ head/contrib/bc/manuals/dc/EN.1 (revision 363810) @@ -1,1198 +1,1199 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/EN.1.md =================================================================== --- head/contrib/bc/manuals/dc/EN.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/EN.1.md (revision 363810) @@ -1,1025 +1,1025 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/ENP.1 =================================================================== --- head/contrib/bc/manuals/dc/ENP.1 (revision 363809) +++ head/contrib/bc/manuals/dc/ENP.1 (revision 363810) @@ -1,1191 +1,1192 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/ENP.1.md =================================================================== --- head/contrib/bc/manuals/dc/ENP.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/ENP.1.md (revision 363810) @@ -1,1020 +1,1020 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/EP.1 =================================================================== --- head/contrib/bc/manuals/dc/EP.1 (revision 363809) +++ head/contrib/bc/manuals/dc/EP.1 (revision 363810) @@ -1,1195 +1,1196 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]2\f[]. Values are output in the specified base. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], and \f[B]scale\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]2\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], taking the square root of a negative number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]) operator. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/EP.1.md =================================================================== --- head/contrib/bc/manuals/dc/EP.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/EP.1.md (revision 363810) @@ -1,1025 +1,1025 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 **2**. Values are output in the specified base. 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/H.1 =================================================================== --- head/contrib/bc/manuals/dc/H.1 (revision 363809) +++ head/contrib/bc/manuals/dc/H.1 (revision 363810) @@ -1,1391 +1,1392 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/H.1.md =================================================================== --- head/contrib/bc/manuals/dc/H.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/H.1.md (revision 363810) @@ -1,1181 +1,1181 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/HN.1 =================================================================== --- head/contrib/bc/manuals/dc/HN.1 (revision 363809) +++ head/contrib/bc/manuals/dc/HN.1 (revision 363810) @@ -1,1387 +1,1388 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/HN.1.md =================================================================== --- head/contrib/bc/manuals/dc/HN.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/HN.1.md (revision 363810) @@ -1,1176 +1,1176 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/HNP.1 =================================================================== --- head/contrib/bc/manuals/dc/HNP.1 (revision 363809) +++ head/contrib/bc/manuals/dc/HNP.1 (revision 363810) @@ -1,1380 +1,1381 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/HNP.1.md =================================================================== --- head/contrib/bc/manuals/dc/HNP.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/HNP.1.md (revision 363810) @@ -1,1171 +1,1171 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/HP.1 =================================================================== --- head/contrib/bc/manuals/dc/HP.1 (revision 363809) +++ head/contrib/bc/manuals/dc/HP.1 (revision 363810) @@ -1,1384 +1,1385 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/HP.1.md =================================================================== --- head/contrib/bc/manuals/dc/HP.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/HP.1.md (revision 363810) @@ -1,1176 +1,1176 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the default handler for all other signals. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/N.1 =================================================================== --- head/contrib/bc/manuals/dc/N.1 (revision 363809) +++ head/contrib/bc/manuals/dc/N.1 (revision 363810) @@ -1,1402 +1,1403 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[] section) This is mostly for those users that do not want a prompt or are not used to having them in dc(1). Most of those users would want to put this option in \f[B]DC_ENV_ARGS\f[]. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP The prompt is enabled in TTY mode. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/N.1.md =================================================================== --- head/contrib/bc/manuals/dc/N.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/N.1.md (revision 363810) @@ -1,1189 +1,1189 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. The prompt is enabled in TTY mode. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/NP.1 =================================================================== --- head/contrib/bc/manuals/dc/NP.1 (revision 363809) +++ head/contrib/bc/manuals/dc/NP.1 (revision 363810) @@ -1,1395 +1,1396 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/NP.1.md =================================================================== --- head/contrib/bc/manuals/dc/NP.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/NP.1.md (revision 363810) @@ -1,1184 +1,1184 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc/P.1 =================================================================== --- head/contrib/bc/manuals/dc/P.1 (revision 363809) +++ head/contrib/bc/manuals/dc/P.1 (revision 363810) @@ -1,1399 +1,1400 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2020 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "DC" "1" "July 2020" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc \- arbitrary\-precision reverse\-Polish notation calculator .SH SYNOPSIS .PP \f[B]dc\f[] [\f[B]\-hiPvVx\f[]] [\f[B]\-\-version\f[]] [\f[B]\-\-help\f[]] [\f[B]\-\-interactive\f[]] [\f[B]\-\-no\-prompt\f[]] [\f[B]\-\-extended\-register\f[]] [\f[B]\-e\f[] \f[I]expr\f[]] [\f[B]\-\-expression\f[]=\f[I]expr\f[]...] [\f[B]\-f\f[] \f[I]file\f[]...] [\f[B]\-file\f[]=\f[I]file\f[]...] [\f[I]file\f[]...] .SH DESCRIPTION .PP dc(1) is an arbitrary\-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. .PP If no files are given on the command\-line as extra arguments (i.e., not as \f[B]\-f\f[] or \f[B]\-\-file\f[] arguments), then dc(1) reads from \f[B]stdin\f[]. Otherwise, those files are processed, and dc(1) will then exit. .PP This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where \f[B]\-e\f[] (\f[B]\-\-expression\f[]) and \f[B]\-f\f[] (\f[B]\-\-file\f[]) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable \f[B]DC_ENV_ARGS\f[] (see the \f[B]ENVIRONMENT VARIABLES\f[] section). Any expressions given on the command\-line should be used to set up a standard environment. For example, if a user wants the \f[B]scale\f[] always set to \f[B]10\f[], they can set \f[B]DC_ENV_ARGS\f[] to \f[B]\-e 10k\f[], and this dc(1) will always start with a \f[B]scale\f[] of \f[B]10\f[]. .PP If users want to have dc(1) exit after processing all input from \f[B]\-e\f[] and \f[B]\-f\f[] arguments (and their equivalents), then they can just simply add \f[B]\-e q\f[] as the last command\-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP .B \f[B]\-h\f[], \f[B]\-\-help\f[] Prints a usage message and quits. .RS .RE .TP .B \f[B]\-v\f[], \f[B]\-V\f[], \f[B]\-\-version\f[] Print the version information (copyright header) and exit. .RS .RE .TP .B \f[B]\-i\f[], \f[B]\-\-interactive\f[] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[] section.) .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-P\f[], \f[B]\-\-no\-prompt\f[] This option is a no\-op. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-x\f[] \f[B]\-\-extended\-register\f[] Enables extended register mode. See the \f[I]Extended Register Mode\f[] subsection of the \f[B]REGISTERS\f[] section for more information. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-e\f[] \f[I]expr\f[], \f[B]\-\-expression\f[]=\f[I]expr\f[] Evaluates \f[I]expr\f[]. 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. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the expressions and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\-f\f[] \f[I]file\f[], \f[B]\-\-file\f[]=\f[I]file\f[] Reads in \f[I]file\f[] and evaluates it, line by line, as though it were read through \f[B]stdin\f[]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP -In other dc(1) implementations, this option causes the program to -execute the files and then exit. -This dc(1) does not, unless the \f[B]DC_EXPR_EXIT\f[] is defined (see -the \f[B]ENVIRONMENT VARIABLES\f[] section). +After processing all expressions and files, dc(1) will exit, unless +\f[B]\-\f[] (\f[B]stdin\f[]) was given as an argument at least once to +\f[B]\-f\f[] or \f[B]\-\-file\f[]. +However, if any other \f[B]\-e\f[], \f[B]\-\-expression\f[], +\f[B]\-f\f[], or \f[B]\-\-file\f[] arguments are given after that, bc(1) +will give a fatal error and exit. .PP This is a \f[B]non\-portable extension\f[]. .RE .PP All long options are \f[B]non\-portable extensions\f[]. .SH STDOUT .PP Any non\-error output is written to \f[B]stdout\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stdout\f[], so if \f[B]stdout\f[] is closed, as in \f[B]dc >&\-\f[], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stdout\f[] to \f[B]/dev/null\f[]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[]. .PP \f[B]Note\f[]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[] section) if it cannot write to \f[B]stderr\f[], so if \f[B]stderr\f[] is closed, as in \f[B]dc 2>&\-\f[], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[] is redirected to a file. .PP If there are scripts that depend on the behavior of other dc(1) implementations, it is recommended that those scripts be changed to redirect \f[B]stderr\f[] to \f[B]/dev/null\f[]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[] section) or a command (see the \f[B]COMMANDS\f[] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. \f[B]ibase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]ibase\f[] is \f[B]16\f[]. The min allowable value for \f[B]ibase\f[] is \f[B]2\f[]. The max allowable value for \f[B]ibase\f[] can be queried in dc(1) programs with the \f[B]T\f[] command. .PP \f[B]obase\f[] is a register (see the \f[B]REGISTERS\f[] section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. \f[B]obase\f[] is initially \f[B]10\f[]. The max allowable value for \f[B]obase\f[] is \f[B]DC_BASE_MAX\f[] and can be queried with the \f[B]U\f[] command. The min allowable value for \f[B]obase\f[] is \f[B]0\f[]. If \f[B]obase\f[] is \f[B]0\f[], values are output in scientific notation, and if \f[B]obase\f[] is \f[B]1\f[], values are output in engineering notation. Otherwise, values are output in the specified base. .PP Outputting in scientific and engineering notations are \f[B]non\-portable extensions\f[]. .PP The \f[I]scale\f[] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[] is a register (see the \f[B]REGISTERS\f[] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[] is initially \f[B]0\f[]. \f[B]scale\f[] cannot be negative. The max allowable value for \f[B]scale\f[] can be queried in dc(1) programs with the \f[B]V\f[] command. .PP \f[B]seed\f[] is a register containing the current seed for the pseudo\-random number generator. If the current value of \f[B]seed\f[] is queried and stored, then if it is assigned to \f[B]seed\f[] later, the pseudo\-random number generator is guaranteed to produce the same sequence of pseudo\-random numbers that were generated after the value of \f[B]seed\f[] was first queried. .PP Multiple values assigned to \f[B]seed\f[] can produce the same sequence of pseudo\-random numbers. Likewise, when a value is assigned to \f[B]seed\f[], it is not guaranteed that querying \f[B]seed\f[] immediately after will return the same value. In addition, the value of \f[B]seed\f[] will change after any call to the \f[B]\[aq]\f[] command or the \f[B]"\f[] command that does not get receive a value of \f[B]0\f[] or \f[B]1\f[]. The maximum integer returned by the \f[B]\[aq]\f[] command can be queried with the \f[B]W\f[] command. .PP \f[B]Note\f[]: The values returned by the pseudo\-random number generator with the \f[B]\[aq]\f[] and \f[B]"\f[] commands are guaranteed to \f[B]NOT\f[] be cryptographically secure. This is a consequence of using a seeded pseudo\-random number generator. However, they \f[B]are\f[] guaranteed to be reproducible with identical \f[B]seed\f[] values. .PP The pseudo\-random number generator, \f[B]seed\f[], and all associated operations are \f[B]non\-portable extensions\f[]. .SS Comments .PP Comments go from \f[B]#\f[] until, and not including, the next newline. This is a \f[B]non\-portable extension\f[]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[], and at most \f[B]1\f[] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[] digits. Uppercase letters are equal to \f[B]9\f[] + their position in the alphabet (i.e., \f[B]A\f[] equals \f[B]10\f[], or \f[B]9+1\f[]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[], they are set to the value of the highest valid digit in \f[B]ibase\f[]. .PP Single\-character numbers (i.e., \f[B]A\f[] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[]. This means that \f[B]A\f[] alone always equals decimal \f[B]10\f[] and \f[B]F\f[] alone always equals decimal \f[B]15\f[]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[]. The power (the portion after the \f[B]e\f[]) must be an integer. An example is \f[B]1.89237e9\f[], which is equal to \f[B]1892370000\f[]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[] is equal to \f[B]0.0042890\f[]. .PP \f[B]WARNING\f[]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[], but the number is still multiplied by \f[B]10^exponent\f[] regardless of the current \f[B]ibase\f[]. For example, if \f[B]ibase\f[] is \f[B]16\f[] and dc(1) is given the number string \f[B]FFeA\f[], the resulting decimal number will be \f[B]2550000000000\f[], and if dc(1) is given the number string \f[B]10e_4\f[], the resulting decimal number will be \f[B]0.0016\f[]. .PP Accepting input as scientific notation is a \f[B]non\-portable extension\f[]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .PP Note that both scientific notation and engineering notation are available for printing numbers. Scientific notation is activated by assigning \f[B]0\f[] to \f[B]obase\f[] using \f[B]0o\f[], and engineering notation is activated by assigning \f[B]1\f[] to \f[B]obase\f[] using \f[B]1o\f[]. To deactivate them, just assign a different value to \f[B]obase\f[]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non\-portable extension\f[]. .TP .B \f[B]p\f[] Prints the value on top of the stack, whether number or string, and prints a newline after. .RS .PP This does not alter the stack. .RE .TP .B \f[B]n\f[] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .RS .RE .TP .B \f[B]P\f[] Pops a value off the stack. .RS .PP If the value is a number, it is truncated and the absolute value of the result is printed as though \f[B]obase\f[] is \f[B]UCHAR_MAX+1\f[] and each digit is interpreted as an ASCII character, making it a byte stream. .PP If the value is a string, it is printed without a trailing newline. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]f\f[] Prints the entire contents of the stack, in order from newest to oldest, without altering anything. .RS .PP Users should use this command when they get lost. .RE .SS Arithmetic .PP These are the commands used for arithmetic. .TP .B \f[B]+\f[] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]\-\f[] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to the max \f[I]scale\f[] of both operands. .RS .RE .TP .B \f[B]*\f[] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[] is the \f[I]scale\f[] of the first expression and \f[B]b\f[] is the \f[I]scale\f[] of the second expression, the \f[I]scale\f[] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[] where \f[B]min()\f[] and \f[B]max()\f[] return the obvious values. .RS .RE .TP .B \f[B]/\f[] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]%\f[] The top two values are popped off the stack, remaindered, and the result is pushed onto the stack. .RS .PP Remaindering is equivalent to 1) Computing \f[B]a/b\f[] to current \f[B]scale\f[], and 2) Using the result of step 1 to calculate \f[B]a\-(a/b)*b\f[] to \f[I]scale\f[] \f[B]max(scale+scale(b),scale(a))\f[]. .PP The first value popped off of the stack must be non\-zero. .RE .TP .B \f[B]~\f[] 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 to \f[B]x y / x y %\f[] except that \f[B]x\f[] and \f[B]y\f[] are only evaluated once. .RS .PP The first value popped off of the stack must be non\-zero. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]^\f[] 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. .RS .PP 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. .RE .TP .B \f[B]v\f[] The top value is popped off the stack, its square root is computed, and the result is pushed onto the stack. The \f[I]scale\f[] of the result is equal to \f[B]scale\f[]. .RS .PP The value popped off of the stack must be non\-negative. .RE .TP .B \f[B]_\f[] If this command \f[I]immediately\f[] precedes a number (i.e., no spaces or other commands), then that number is input as a negative number. .RS .PP 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 \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]b\f[] 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. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]|\f[] The top three values are popped off the stack, a modular exponentiation is computed, and the result is pushed onto the stack. .RS .PP 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]$\f[] The top value is popped off the stack and copied, and the copy is truncated and pushed onto the stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]\@\f[] 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. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]H\f[] The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]h\f[] The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. .RS .PP The first value popped off of the stack must be an integer and non\-negative. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]G\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if they are equal, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]N\f[] The top value is popped off of the stack, and if it a \f[B]0\f[], a \f[B]1\f[] is pushed; otherwise, a \f[B]0\f[] is pushed. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B](\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]{\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is less than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B])\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]}\f[] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[] is pushed if the first is greater than or equal to the second, or \f[B]0\f[] otherwise. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]M\f[] The top two values are popped off of the stack. If they are both non\-zero, a \f[B]1\f[] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]m\f[] The top two values are popped off of the stack. If at least one of them is non\-zero, a \f[B]1\f[] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[] operator in bc(1), and it is \f[I]not\f[] a short\-circuit operator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Pseudo\-Random Number Generator .PP dc(1) has a built\-in pseudo\-random number generator. These commands query the pseudo\-random number generator. (See Parameters for more information about the \f[B]seed\f[] value that controls the pseudo\-random number generator.) .PP The pseudo\-random number generator is guaranteed to \f[B]NOT\f[] be cryptographically secure. .TP .B \f[B]\[aq]\f[] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section). .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]"\f[] Pops a value off of the stack, which is used as an \f[B]exclusive\f[] upper bound on the integer that will be generated. If the bound is negative or is a non\-integer, an error is raised, and dc(1) resets (see the \f[B]RESET\f[] section) while \f[B]seed\f[] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[], the higher bound is honored by generating several pseudo\-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[], and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of \f[B]seed\f[], unless the operand is \f[B]0\f[] or \f[B]1\f[]. In that case, \f[B]0\f[] is pushed onto the stack, and \f[B]seed\f[] is \f[I]not\f[] changed. .RS .PP The generated integer is made as unbiased as possible, subject to the limitations of the pseudo\-random number generator. .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Stack Control .PP These commands control the stack. .TP .B \f[B]c\f[] Removes all items from ("clears") the stack. .RS .RE .TP .B \f[B]d\f[] Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. .RS .RE .TP .B \f[B]r\f[] Swaps ("reverses") the two top items on the stack. .RS .RE .TP .B \f[B]R\f[] Pops ("removes") the top value from the stack. .RS .RE .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[] section). .TP .B \f[B]s\f[]\f[I]r\f[] Pops the value off the top of the stack and stores it into register \f[I]r\f[]. .RS .RE .TP .B \f[B]l\f[]\f[I]r\f[] Copies the value in register \f[I]r\f[] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[]. .RS .RE .TP .B \f[B]S\f[]\f[I]r\f[] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[]. The previous value of the register becomes inaccessible. .RS .RE .TP .B \f[B]L\f[]\f[I]r\f[] Pops the value off the top of the stack for register \f[I]r\f[] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[], if any, is now accessible via the \f[B]l\f[]\f[I]r\f[] command. .RS .RE .SS Parameters .PP These commands control the values of \f[B]ibase\f[], \f[B]obase\f[], \f[B]scale\f[], and \f[B]seed\f[]. Also see the \f[B]SYNTAX\f[] section. .TP .B \f[B]i\f[] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[], which must be between \f[B]2\f[] and \f[B]16\f[], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]o\f[] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[], which must be between \f[B]0\f[] and \f[B]DC_BASE_MAX\f[], inclusive (see the \f[B]LIMITS\f[] section and the \f[B]NUMBERS\f[] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]k\f[] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[], which must be non\-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[], the \f[I]scale\f[] is ignored. .RE .TP .B \f[B]j\f[] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[]. The meaning of \f[B]seed\f[] is dependent on the current pseudo\-random number generator but is guaranteed to not change except for new major versions. .RS .PP The \f[I]scale\f[] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[] 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 \f[B]seed\f[] value was previously used. .PP The exact value assigned to \f[B]seed\f[] is not guaranteed to be returned if the \f[B]J\f[] command is used. However, if \f[B]seed\f[] \f[I]does\f[] return a different value, both values, when assigned to \f[B]seed\f[], are guaranteed to produce the same sequence of pseudo\-random numbers. This means that certain values assigned to \f[B]seed\f[] will not produce unique sequences of pseudo\-random numbers. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[] of the value that can be assigned to \f[B]seed\f[]. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]I\f[] Pushes the current value of \f[B]ibase\f[] onto the main stack. .RS .RE .TP .B \f[B]O\f[] Pushes the current value of \f[B]obase\f[] onto the main stack. .RS .RE .TP .B \f[B]K\f[] Pushes the current value of \f[B]scale\f[] onto the main stack. .RS .RE .TP .B \f[B]J\f[] Pushes the current value of \f[B]seed\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]T\f[] Pushes the maximum allowable value of \f[B]ibase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]U\f[] Pushes the maximum allowable value of \f[B]obase\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]V\f[] Pushes the maximum allowable value of \f[B]scale\f[] onto the main stack. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]W\f[] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[aq]\f[] pseudo\-random number generator command. .RS .PP This is a \f[B]non\-portable extension\f[]. .RE .SS Strings .PP The following commands control strings. .PP dc(1) can work with both numbers and strings, and registers (see the \f[B]REGISTERS\f[] section) can hold both strings and numbers. dc(1) always knows whether the contents of a register are a string or a number. .PP While arithmetic operations have to have numbers, and will print an error if given a string, other commands accept strings. .PP Strings can also be executed as macros. For example, if the string \f[B][1pR]\f[] is executed as a macro, then the code \f[B]1pR\f[] is executed, meaning that the \f[B]1\f[] will be printed with a newline after and then popped from the stack. .TP .B \f[B][\f[]\f[I]characters\f[]\f[B]]\f[] Makes a string containing \f[I]characters\f[] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[] and \f[B]]\f[]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\\\f[]) character. .PP If there is 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. .RE .TP .B \f[B]a\f[] The value on top of the stack is popped. .RS .PP If it is a number, it is truncated and its absolute value is taken. The result mod \f[B]UCHAR_MAX+1\f[] is calculated. If that result is \f[B]0\f[], push an empty string; otherwise, push a one\-character string where the character is the result of the mod interpreted as an ASCII character. .PP If it is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]x\f[] Pops a value off of the top of the stack. .RS .PP If it is a number, it is pushed back onto the stack. .PP If it is a string, it is executed as a macro. .PP This behavior is the norm whenever a macro is executed, whether by this command or by the conditional execution commands below. .RE .TP .B \f[B]>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP For example, \f[B]0 1>a\f[] will execute the contents of register \f[B]a\f[], and \f[B]1 0>a\f[] will not. .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!>\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!>\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!<\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!<\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]!=\f[]\f[I]r\f[] Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register \f[I]r\f[] are executed. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .RE .TP .B \f[B]!=\f[]\f[I]r\f[]\f[B]e\f[]\f[I]s\f[] Like the above, but will execute register \f[I]s\f[] if the comparison fails. .RS .PP If either or both of the values are not numbers, dc(1) will raise an error and reset (see the \f[B]RESET\f[] section). .PP This is a \f[B]non\-portable extension\f[]. .RE .TP .B \f[B]?\f[] Reads a line from the \f[B]stdin\f[] and executes it. This is to allow macros to request input from users. .RS .RE .TP .B \f[B]q\f[] 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. .RS .RE .TP .B \f[B]Q\f[] Pops a value from the stack which must be non\-negative and is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. .RS .RE .SS Status .PP These commands query status of the stack or its top value. .TP .B \f[B]Z\f[] Pops a value off of the stack. .RS .PP If it is a number, calculates the number of significant decimal digits it has and pushes the result. .PP If it is a string, pushes the number of characters the string has. .RE .TP .B \f[B]X\f[] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[]. .RE .TP .B \f[B]z\f[] Pushes the current stack depth (before execution of this command). .RS .RE .SS Arrays .PP These commands manipulate arrays. .TP .B \f[B]:\f[]\f[I]r\f[] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[] (see the \f[B]REGISTERS\f[] section), indexed by the first value. .RS .RE .TP .B \f[B];\f[]\f[I]r\f[] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[]. The selected value is then pushed onto the stack. .RS .RE .SH REGISTERS .PP Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) .PP Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (\f[B]0\f[]) in their stack. .PP In non\-extended register mode, a register name is just the single character that follows any command that needs a register name. The only exception is a newline (\f[B]\[aq]\\n\[aq]\f[]); it is a parse error for a newline to be used as a register name. .SS Extended Register Mode .PP Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. .PP If extended register mode is enabled (\f[B]\-x\f[] or \f[B]\-\-extended\-register\f[] command\-line arguments are given), then normal single character registers are used \f[I]unless\f[] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[]) and not a newline (\f[B]\[aq]\\n\[aq]\f[]). .PP In that case, the register name is found according to the regex \f[B][a\-z][a\-z0\-9_]*\f[] (like bc(1) identifiers), and it is a parse error if the next non\-space characters do not match that regex. .SH RESET .PP 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. .PP First, any macros that are executing are stopped and popped off the 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. .PP Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is interactive mode, and the error was not a fatal error (see the \f[B]EXIT STATUS\f[] section), it asks for more input; otherwise, it exits with the appropriate return code. .SH PERFORMANCE .PP Most dc(1) implementations use \f[B]char\f[] types to calculate the value of \f[B]1\f[] decimal digit at a time, but that can be slow. This dc(1) does something different. .PP It uses large integers to calculate more than \f[B]1\f[] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[] (see the \f[B]LIMITS\f[] section) is \f[B]64\f[], then each integer has \f[B]9\f[] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[] is \f[B]32\f[] then each integer has \f[B]4\f[] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[]. .PP In addition, this dc(1) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]DC_LONG_BIT\f[], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on dc(1): .TP .B \f[B]DC_LONG_BIT\f[] The number of bits in the \f[B]long\f[] type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[] section). .RS .RE .TP .B \f[B]DC_BASE_DIGS\f[] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[] section). Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_POW\f[] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[]) plus \f[B]1\f[]. Depends on \f[B]DC_BASE_DIGS\f[]. .RS .RE .TP .B \f[B]DC_OVERFLOW_MAX\f[] The max number that the overflow type (see the \f[B]PERFORMANCE\f[] section) can hold. Depends on \f[B]DC_LONG_BIT\f[]. .RS .RE .TP .B \f[B]DC_BASE_MAX\f[] The maximum output base. Set at \f[B]DC_BASE_POW\f[]. .RS .RE .TP .B \f[B]DC_DIM_MAX\f[] The maximum size of arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_SCALE_MAX\f[] The maximum \f[B]scale\f[]. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_STRING_MAX\f[] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NAME_MAX\f[] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_NUM_MAX\f[] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]DC_OVERFLOW_MAX\-1\f[]. .RS .RE .TP .B \f[B]DC_RAND_MAX\f[] The maximum integer (inclusive) returned by the \f[B]\[aq]\f[] command, if dc(1). Set at \f[B]2^DC_LONG_BIT\-1\f[]. .RS .RE .TP .B Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[]. .RS .RE .TP .B Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX\-1\f[]. .RS .RE .PP These limits are meant to be effectively non\-existent; the limits are so large (at least on 64\-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH ENVIRONMENT VARIABLES .PP dc(1) recognizes the following environment variables: .TP .B \f[B]DC_ENV_ARGS\f[] This is another way to give command\-line arguments to dc(1). They should be in the same format as all other command\-line arguments. These are always processed first, so any files given in \f[B]DC_ENV_ARGS\f[] will be processed before arguments and files given on the command\-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the \f[B]\-e\f[] option to set \f[B]scale\f[] to a value other than \f[B]0\f[]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]"/home/gavin/some dc file.dc"\f[] will be correctly parsed, but the string \f[B]"/home/gavin/some "dc" file.dc"\f[] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[aq]\f[] or \f[B]"\f[]. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in \f[B]"some \[aq]bc\[aq] file.bc"\f[], and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in \f[B]DC_ENV_ARGS\f[] is not supported due to the complexity of the parsing, though such files are still supported on the command\-line where the parsing is done by the shell. .RE .TP .B \f[B]DC_LINE_LENGTH\f[] If this environment variable exists and contains an integer that is greater than \f[B]1\f[] and is less than \f[B]UINT16_MAX\f[] (\f[B]2^16\-1\f[]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[]. .RS .RE .TP .B \f[B]DC_EXPR_EXIT\f[] If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the \f[B]\-e\f[] and/or \f[B]\-f\f[] command\-line options (and any equivalents). .RS .RE .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP .B \f[B]0\f[] No error. .RS .RE .TP .B \f[B]1\f[] A math error occurred. This follows standard practice of using \f[B]1\f[] for expected errors, since math errors will happen in the process of normal execution. .RS .PP Math errors include divide by \f[B]0\f[], 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, and attempting to use a non\-integer where an integer is required. .PP Converting to a hardware integer happens for the second operand of the power (\f[B]^\f[]), places (\f[B]\@\f[]), left shift (\f[B]H\f[]), and right shift (\f[B]h\f[]) operators. .RE .TP .B \f[B]2\f[] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP .B \f[B]3\f[] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[], \f[B]obase\f[], or \f[B]scale\f[]; give a bad expression to a \f[B]read()\f[] call, calling \f[B]read()\f[] inside of a \f[B]read()\f[] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP .B \f[B]4\f[] A fatal error occurred. .RS .PP 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. .RE .PP The exit status \f[B]4\f[] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[], no matter what mode dc(1) is in. .PP The other statuses will only be returned when dc(1) is not in interactive mode (see the \f[B]INTERACTIVE MODE\f[] section), since dc(1) resets its state (see the \f[B]RESET\f[] 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .PP 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 \f[B]\-i\f[] flag or \f[B]\-\-interactive\f[] option. .SH INTERACTIVE MODE .PP Like bc(1), dc(1) has an interactive mode and a non\-interactive mode. Interactive mode is turned on automatically when both \f[B]stdin\f[] and \f[B]stdout\f[] are hooked to a terminal, but the \f[B]\-i\f[] flag and \f[B]\-\-interactive\f[] option can turn it on in other cases. .PP In interactive mode, dc(1) attempts to recover from errors (see the \f[B]RESET\f[] section), and in normal execution, flushes \f[B]stdout\f[] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[], \f[B]stdout\f[], and \f[B]stderr\f[] are all connected to a TTY, dc(1) turns on "TTY mode." .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[] section). It is also required to enable special handling for \f[B]SIGINT\f[] signals. .PP TTY mode is different from interactive mode because interactive mode is required in the bc(1) specification (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html), and interactive mode requires only \f[B]stdin\f[] and \f[B]stdout\f[] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[] will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), it will reset (see the \f[B]RESET\f[] section). Otherwise, it will clean up and exit. .PP Note that "current input" can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[] in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY mode, it will stop processing the file and start processing the next file, if one exists, or ask for input from \f[B]stdin\f[] if no other file exists. .PP This means that if a \f[B]SIGINT\f[] is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. .PP \f[B]SIGTERM\f[] and \f[B]SIGQUIT\f[] cause dc(1) to clean up and exit, and it uses the default handler for all other signals. The one exception is \f[B]SIGHUP\f[]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[] will cause dc(1) to clean up and exit. .SH COMMAND LINE HISTORY .PP dc(1) supports interactive command\-line editing. If dc(1) is in TTY mode (see the \f[B]TTY MODE\f[] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[]: tabs are converted to 8 spaces. .SH LOCALES .PP This dc(1) ships with support for adding error messages for different locales and thus, supports \f[B]LC_MESSAGS\f[]. .SH SEE ALSO .PP bc(1) .SH STANDARDS .PP The dc(1) utility operators are compliant with the operators in the bc(1) IEEE Std 1003.1\-2017 (“POSIX.1\-2017”) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHOR .PP Gavin D. Howard and contributors. Index: head/contrib/bc/manuals/dc/P.1.md =================================================================== --- head/contrib/bc/manuals/dc/P.1.md (revision 363809) +++ head/contrib/bc/manuals/dc/P.1.md (revision 363810) @@ -1,1189 +1,1189 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** : This option is a no-op. This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **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 get 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. 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, which must be between **0** and **DC_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 of the top of the stack and uses it to set **scale**, 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 of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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, 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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **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, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/manuals/dc.1.md.in =================================================================== --- head/contrib/bc/manuals/dc.1.md.in (revision 363809) +++ head/contrib/bc/manuals/dc.1.md.in (revision 363810) @@ -1,1257 +1,1257 @@ # Name dc - arbitrary-precision reverse-Polish notation calculator # SYNOPSIS **dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] # DESCRIPTION dc(1) is an arbitrary-precision calculator. It uses a stack (reverse Polish notation) to store numbers and results of computations. Arithmetic operations pop arguments off of the stack and push the results. If no files are given on the command-line as extra arguments (i.e., not as **-f** or **--file** arguments), then dc(1) reads from **stdin**. Otherwise, those files are processed, and dc(1) will then exit. This is different from the dc(1) on OpenBSD and possibly other dc(1) implementations, where **-e** (**--expression**) and **-f** (**--file**) arguments cause dc(1) to execute them and exit. The reason for this is that this dc(1) allows users to set arguments in the environment variable **DC_ENV_ARGS** (see the **ENVIRONMENT VARIABLES** section). Any expressions given on the command-line should be used to set up a standard environment. 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**. If users want to have dc(1) exit after processing all input from **-e** and **-f** arguments (and their equivalents), then they can just simply add **-e q** as the last command-line argument or define the environment variable **DC_EXPR_EXIT**. # OPTIONS The following are the options that dc(1) accepts. **-h**, **--help** : Prints a usage message and quits. **-v**, **-V**, **--version** : Print the version information (copyright header) and exit. **-i**, **--interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. **-P**, **--no-prompt** {{ A E H N EH EN HN EHN }} : 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 in dc(1). Most of those users would want to put this option in **DC_ENV_ARGS**. {{ end }} {{ P EP HP NP EHP ENP HNP EHNP }} : This option is a no-op. {{ end }} This is a **non-portable extension**. **-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**. **-e** *expr*, **--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. - In other dc(1) implementations, this option causes the program to execute - the expressions and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + After processing all expressions and files, dc(1) will exit, unless **-** + (**stdin**) was given as an argument at least once to **-f** or **--file**. This is a **non-portable extension**. **-f** *file*, **--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. - In other dc(1) implementations, this option causes the program to execute - the files and then exit. This dc(1) does not, unless the - **DC_EXPR_EXIT** is defined (see the **ENVIRONMENT VARIABLES** section). + 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 that, bc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. **Note**: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stdout**, so if **stdout** is closed, as in **dc >&-**, it will quit with an error. This is done so that dc(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 other dc(1) implementations, this dc(1) will issue a fatal error (see the **EXIT STATUS** section) if it cannot write to **stderr**, so if **stderr** is closed, as in **dc 2>&-**, it will quit with an error. This is done so that dc(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 Each item in the input source code, either a number (see the **NUMBERS** section) or a command (see the **COMMANDS** section), is processed and executed, in order. Input is processed immediately when entered. **ibase** is a register (see the **REGISTERS** section) that determines how to interpret constant numbers. It is the "input" base, or the number base used for interpreting input numbers. **ibase** is initially **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 the **REGISTERS** section) that determines how to output results. It is the "output" base, or the number base used for outputting numbers. **obase** is initially **10**. The max allowable value for **obase** is **DC_BASE_MAX** and can be queried with the **U** command. The min allowable {{ A H N P HN HP NP HNP }} 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**. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} value for **obase** is **2**. Values are output in the specified base. {{ end }} 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 the **REGISTERS** section) that sets the precision of any operations (with exceptions). **scale** is initially **0**. **scale** cannot be negative. The max allowable value for **scale** can be queried in dc(1) programs with the **V** command. {{ A H N P HN HP NP HNP }} **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 get 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. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. {{ end }} ## 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** + 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**, they are set to the value of the highest valid digit in **ibase**. Single-character numbers (i.e., **A** alone) take the value that they would have if they were valid digits, regardless of the value of **ibase**. This means that **A** alone always equals decimal **10** and **F** alone always equals decimal **15**. {{ A H N P HN HP NP HNP }} In addition, dc(1) accepts numbers in scientific notation. These have the form **\e\**. The power (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 current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and dc(1) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if dc(1) is given the number string **10e_4**, the resulting decimal number will be **0.0016**. Accepting input as scientific notation is a **non-portable extension**. {{ end }} # COMMANDS The valid commands are listed below. ## Printing These commands are used for printing. {{ A H N P HN HP NP HNP }} 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**. {{ end }} **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 though **obase** is **UCHAR_MAX+1** and each digit is interpreted as an 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. If **a** is the *scale* of the first expression and **b** is the *scale* of the second expression, the *scale* of the result is equal to **min(a+b,max(scale,a,b))** where **min()** and **max()** 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 to **scale**. 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) Computing **a/b** to current **scale**, and 2) Using the result of step 1 to calculate **a-(a/b)\*b** to *scale* **max(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 to **x y / x y %** except that **x** and **y** are 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 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 to **scale**. 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**. {{ A H N P HN HP NP HNP }} **\$** : 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. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **H** : The top two values are popped off the stack, and the second is shifted left (radix shifted right) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. **h** : The top two values are popped off the stack, and the second is shifted right (radix shifted left) to the value of the first. The first value popped off of the stack must be an integer and non-negative. This is a **non-portable extension**. {{ end }} **G** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if they are equal, or **0** otherwise. This is a **non-portable extension**. **N** : The top value is popped off of the stack, and if it a **0**, a **1** is pushed; otherwise, a **0** is pushed. This is a **non-portable extension**. **(** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than the second, or **0** otherwise. This is a **non-portable extension**. **{** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is less than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **)** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than the second, or **0** otherwise. This is a **non-portable extension**. **}** : The top two values are popped off of the stack, they are compared, and a **1** is pushed if the first is greater than or equal to the second, or **0** otherwise. This is a **non-portable extension**. **M** : The top two values are popped off of the stack. If they are both non-zero, a **1** is pushed onto the stack. If either of them is zero, or both of them are, then a **0** is pushed onto the stack. This is like the **&&** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. **m** : The top two values are popped off of the stack. If at least one of them is non-zero, a **1** is pushed onto the stack. If both of them are zero, then a **0** is pushed onto the stack. This is like the **||** operator in bc(1), and it is *not* a short-circuit operator. This is a **non-portable extension**. {{ A H N P HN HP NP HNP }} ## Pseudo-Random Number Generator dc(1) has a built-in pseudo-random number generator. These commands query the pseudo-random number generator. (See Parameters for more information about the **seed** value that controls the pseudo-random number generator.) The pseudo-random number generator is guaranteed to **NOT** be cryptographically secure. **'** : Generates an integer between 0 and **DC_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. This is a **non-portable extension**. **"** : Pops a value off of the stack, which is used as an **exclusive** upper bound on the integer that will be generated. If the bound is negative or is a non-integer, an error is raised, and dc(1) resets (see the **RESET** section) while **seed** remains unchanged. If the bound is larger than **DC_RAND_MAX**, the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of **DC_RAND_MAX+1**, and adding them together. Thus, the size of integer that can be generated with this command is unbounded. Using this command will change the value of **seed**, unless the operand is **0** or **1**. In that case, **0** is pushed onto the stack, and **seed** is *not* changed. The generated integer is made as unbiased as possible, subject to the limitations of the pseudo-random number generator. This is a **non-portable extension**. {{ end }} ## Stack Control These commands control the stack. **c** : Removes all items from ("clears") the stack. **d** : Copies the item on top of the stack ("duplicates") and pushes the copy onto the stack. **r** : Swaps ("reverses") the two top items on the stack. **R** : Pops ("removes") the top value from the stack. ## Register Control These commands control registers (see the **REGISTERS** section). **s***r* : Pops the value off the top of the stack and stores it into register *r*. **l***r* : Copies the value in register *r* and pushes it onto the stack. This does not alter the contents of *r*. **S***r* : Pops the value off the top of the (main) stack and pushes it onto the stack of register *r*. The previous value of the register becomes inaccessible. **L***r* : Pops the value off the top of the stack for register *r* and push it onto the main stack. The previous value in the stack for register *r*, if any, is now accessible via the **l***r* command. ## Parameters {{ A H N P HN HP NP HNP }} These commands control the values of **ibase**, **obase**, **scale**, and **seed**. Also see the **SYNTAX** section. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} These commands control the values of **ibase**, **obase**, and **scale**. Also see the **SYNTAX** section. {{ end }} **i** : Pops the value off of the top of the stack and uses it to set **ibase**, which must be between **2** and **16**, inclusive. If the value on top of the stack has any *scale*, the *scale* is ignored. **o** : Pops the value off of the top of the stack and uses it to set **obase**, {{ A H N P HN HP NP HNP }} which must be between **0** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section and the **NUMBERS** section). {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} which must be between **2** and **DC_BASE_MAX**, inclusive (see the **LIMITS** section). {{ end }} If the value on top of the stack has any *scale*, the *scale* is ignored. **k** : Pops the value off of the top of the stack and uses it to set **scale**, which must be non-negative. If the value on top of the stack has any *scale*, the *scale* is ignored. {{ A H N P HN HP NP HNP }} **j** : Pops the value off of the top of the stack and uses it to set **seed**. The meaning of **seed** is dependent on the current pseudo-random number generator but is 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. 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**. This is a **non-portable extension**. {{ end }} **I** : Pushes the current value of **ibase** onto the main stack. **O** : Pushes the current value of **obase** onto the main stack. **K** : Pushes the current value of **scale** onto the main stack. {{ A H N P HN HP NP HNP }} **J** : Pushes the current value of **seed** onto the main stack. This is a **non-portable extension**. {{ end }} **T** : Pushes the maximum allowable value of **ibase** onto the main stack. This is a **non-portable extension**. **U** : Pushes the maximum allowable value of **obase** onto the main stack. This is a **non-portable extension**. **V** : Pushes the maximum allowable value of **scale** onto the main stack. This is a **non-portable extension**. {{ A H N P HN HP NP HNP }} **W** : Pushes the maximum (inclusive) integer that can be generated with the **'** pseudo-random number generator command. This is a **non-portable extension**. {{ end }} ## 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. 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. **\[**_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. If there is 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 is a number, it is truncated and its absolute value is taken. The result mod **UCHAR_MAX+1** is calculated. If that result is **0**, 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 is a string, then a new string is made. If the original string is empty, the new string is empty. If it is 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. This is a **non-portable extension**. **x** : Pops a value off of the top of the stack. If it is a number, it is pushed back onto the stack. If it is a string, it is 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 of the stack that must be numbers and compares them. If the first value is greater than the second, then the contents of register *r* are executed. For example, **0 1>a** will execute the contents of register **a**, and **1 0>a** will not. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\>***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not greater than the second (less than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\>***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is less than the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!\<***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not less than the second (greater than or equal to), then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!\<***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **!=***r* : Pops two values off of the stack that must be numbers and compares them. If the first value is not equal to the second, then the contents of register *r* are executed. If either or both of the values are not numbers, dc(1) will raise an error and reset (see the **RESET** section). **!=***r***e***s* : Like the above, but will 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 the **RESET** section). This is a **non-portable extension**. **?** : Reads a line from the **stdin** and executes it. This is to allow macros to 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 is used the number of macro executions to pop off of the execution stack. If the number of levels to pop is greater than the number of executing macros, dc(1) exits. ## Status These commands query status of the stack or its top value. **Z** : Pops a value off of the stack. If it is a number, calculates the number of significant decimal digits it has and pushes the result. If it is a string, pushes the number of characters the string has. **X** : Pops a value off of the stack. If it is a number, pushes the *scale* of the value onto the stack. If it is a string, pushes **0**. **z** : Pushes the current stack depth (before execution of this command). ## Arrays These commands manipulate arrays. **:***r* : Pops the top two values off of the stack. The second value will be stored in the array *r* (see the **REGISTERS** section), 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. # REGISTERS Registers are names that can store strings, numbers, and arrays. (Number/string registers do not interfere with array registers.) Each register is also its own stack, so the current register value is the top of the stack for the register. All registers, when first referenced, have one value (**0**) in their 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 exception is a newline (**'\\n'**); it is a parse error for a newline to be used as a register name. ## Extended Register Mode Unlike most other dc(1) implentations, this dc(1) provides nearly unlimited amounts of registers, if extended register mode is enabled. 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 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. Thus, when dc(1) resets, it skips any remaining code waiting to be executed. Then, if it is 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. # 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 a 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. # LIMITS The following are the limits on dc(1): **DC_LONG_BIT** : The number of bits in the **long** type in the environment where dc(1) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **DC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **DC_LONG_BIT**. **DC_BASE_POW** : The max decimal number that each large integer can store (see **DC_BASE_DIGS**) plus **1**. Depends on **DC_BASE_DIGS**. **DC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **DC_LONG_BIT**. **DC_BASE_MAX** : The maximum output base. Set at **DC_BASE_POW**. **DC_DIM_MAX** : The maximum size of arrays. Set at **SIZE_MAX-1**. **DC_SCALE_MAX** : The maximum **scale**. Set at **DC_OVERFLOW_MAX-1**. **DC_STRING_MAX** : The maximum length of strings. Set at **DC_OVERFLOW_MAX-1**. **DC_NAME_MAX** : The maximum length of identifiers. Set at **DC_OVERFLOW_MAX-1**. **DC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **DC_OVERFLOW_MAX-1**. {{ A H N P HN HP NP HNP }} **DC_RAND_MAX** : The maximum integer (inclusive) returned by the **'** command, if dc(1). Set at **2\^DC_LONG_BIT-1**. {{ end }} 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**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # ENVIRONMENT VARIABLES dc(1) recognizes the following environment variables: **DC_ENV_ARGS** : This is another way to give command-line arguments to dc(1). They should be in the same format as all other command-line arguments. These are always processed first, so any files given in **DC_ENV_ARGS** will be processed before arguments and files given on the command-line. This gives the user the ability to set up "standard" options and files to be used at every invocation. The most useful thing for such files to contain would be useful functions that the user might want every time dc(1) runs. Another use would be to use the **-e** option to set **scale** to a value other than **0**. The code that parses **DC_ENV_ARGS** will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string **"/home/gavin/some dc file.dc"** will be correctly parsed, but the string **"/home/gavin/some \"dc\" file.dc"** will include the backslashes. The quote parsing will handle either kind of quotes, **'** or **"**. Thus, if you have a file with any number of single quotes in the name, you can use double quotes as the outside quotes, as in **"some 'bc' file.bc"**, and vice versa if you have a file with double quotes. However, handling a file with both kinds of quotes in **DC_ENV_ARGS** is not supported due to the complexity of the parsing, though such files are still supported on the command-line where the parsing is done by the shell. **DC_LINE_LENGTH** : If this environment variable exists and contains an integer that is greater than **1** and is less than **UINT16_MAX** (**2\^16-1**), dc(1) will output lines to that length, including the backslash newline combo. The default line length is **70**. **DC_EXPR_EXIT** : If this variable exists (no matter the contents), dc(1) will exit immediately after executing expressions and files given by the **-e** and/or **-f** command-line options (and any equivalents). # EXIT STATUS dc(1) returns the following exit statuses: **0** : No error. **1** : A math error occurred. This follows standard practice of using **1** for 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 {{ A H N P HN HP NP HNP }} 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, 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. {{ end }} {{ E EH EN EP EHN EHP ENP EHNP }} number, attempting to convert a negative number to a hardware integer, overflow when converting a number to a hardware integer, 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 (**\^**) operator. {{ end }} **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 **ibase**, **obase**, or **scale**; give a bad expression to a **read()** call, calling **read()** inside of a **read()** call, type errors, 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. The exit status **4** is special; when a fatal error occurs, dc(1) always exits and returns **4**, no matter what mode dc(1) is in. 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 is 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 cases. 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. # TTY MODE If **stdin**, **stdout**, and **stderr** are all connected to a TTY, dc(1) turns on "TTY mode." {{ A E N P EN EP NP ENP }} TTY mode is required for history to be enabled (see the **COMMAND LINE HISTORY** section). It is also required to enable special handling for **SIGINT** signals. {{ end }} {{ A E H N EH EN HN EHN }} The prompt is enabled in TTY mode. {{ end }} TTY mode is different from interactive mode because interactive mode is required in the [bc(1) specification][1], and interactive mode requires only **stdin** and **stdout** to be connected to a terminal. # SIGNAL HANDLING Sending a **SIGINT** will cause dc(1) to stop execution of the current input. If dc(1) is in TTY mode (see the **TTY MODE** section), it will reset (see the **RESET** section). Otherwise, it will clean up and exit. Note that "current input" can mean one of two things. If dc(1) is processing input from **stdin** in TTY mode, it will ask for more input. If dc(1) is processing input from a file in TTY 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 a **SIGINT** is sent to dc(1) as it is executing a file, it can seem as though dc(1) did not respond to the signal since it will immediately start executing the next file. This is by design; most files that users execute when interacting with dc(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. **SIGTERM** and **SIGQUIT** cause dc(1) to clean up and exit, and it uses the {{ A E N P EN EP NP ENP }} default handler for all other signals. The one exception is **SIGHUP**; in that case, when dc(1) is in TTY mode, a **SIGHUP** will cause dc(1) to clean up and exit. {{ end }} {{ H EH HN HP EHN EHP HNP EHNP }} default handler for all other signals. {{ end }} {{ A E N P EN EP NP ENP }} # COMMAND LINE HISTORY dc(1) supports interactive command-line editing. If dc(1) is in TTY mode (see the **TTY MODE** section), history is enabled. Previous lines can be recalled and edited with the arrow keys. **Note**: tabs are converted to 8 spaces. {{ end }} {{ A E H P EH EP HP EHP }} # LOCALES This dc(1) ships with support for adding error messages for different locales and thus, supports **LC_MESSAGS**. {{ end }} # SEE ALSO bc(1) # STANDARDS The dc(1) utility operators are compliant with the operators in the bc(1) [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification. # BUGS None are known. Report bugs at https://git.yzena.com/gavin/bc. # AUTHOR Gavin D. Howard and contributors. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html Index: head/contrib/bc/src/args.c =================================================================== --- head/contrib/bc/src/args.c (revision 363809) +++ head/contrib/bc/src/args.c (revision 363810) @@ -1,215 +1,221 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Code for processing command-line arguments. * */ #include #include #include #include #include #include #include #include #include #include #include #include static const BcOptLong bc_args_lopt[] = { { "expression", BC_OPT_REQUIRED, 'e' }, { "file", BC_OPT_REQUIRED, 'f' }, { "help", BC_OPT_NONE, 'h' }, { "interactive", BC_OPT_NONE, 'i' }, { "no-prompt", BC_OPT_NONE, 'P' }, #if BC_ENABLED { "global-stacks", BC_OPT_BC_ONLY, 'g' }, { "mathlib", BC_OPT_BC_ONLY, 'l' }, { "quiet", BC_OPT_BC_ONLY, 'q' }, { "standard", BC_OPT_BC_ONLY, 's' }, { "warn", BC_OPT_BC_ONLY, 'w' }, #endif // BC_ENABLED { "version", BC_OPT_NONE, 'v' }, { "version", BC_OPT_NONE, 'V' }, #if DC_ENABLED { "extended-register", BC_OPT_DC_ONLY, 'x' }, #endif // DC_ENABLED { NULL, 0, 0 }, }; static void bc_args_exprs(const char *str) { BC_SIG_ASSERT_LOCKED; if (vm.exprs.v == NULL) bc_vec_init(&vm.exprs, sizeof(uchar), NULL); bc_vec_concat(&vm.exprs, str); bc_vec_concat(&vm.exprs, "\n"); } static void bc_args_file(const char *file) { char *buf; BC_SIG_ASSERT_LOCKED; vm.file = file; bc_read_file(file, &buf); bc_args_exprs(buf); free(buf); } void bc_args(int argc, char *argv[]) { int c; size_t i; bool do_exit = false, version = false; BcOpt opts; BC_SIG_ASSERT_LOCKED; bc_opt_init(&opts, argv); while ((c = bc_opt_parse(&opts, bc_args_lopt)) != -1) { switch (c) { case 'e': { + if (vm.no_exit_exprs) + bc_vm_verr(BC_ERROR_FATAL_OPTION, "-e (--expression)"); bc_args_exprs(opts.optarg); break; } case 'f': { - bc_args_file(opts.optarg); + if (!strcmp(opts.optarg, "-")) vm.no_exit_exprs = true; + else { + if (vm.no_exit_exprs) + bc_vm_verr(BC_ERROR_FATAL_OPTION, "-f (--file)"); + bc_args_file(opts.optarg); + } break; } case 'h': { bc_vm_info(vm.help); do_exit = true; break; } case 'i': { vm.flags |= BC_FLAG_I; break; } case 'P': { vm.flags |= BC_FLAG_P; break; } #if BC_ENABLED case 'g': { assert(BC_IS_BC); vm.flags |= BC_FLAG_G; break; } case 'l': { assert(BC_IS_BC); vm.flags |= BC_FLAG_L; break; } case 'q': { assert(BC_IS_BC); - vm.flags |= BC_FLAG_Q; + // Do nothing. break; } case 's': { assert(BC_IS_BC); vm.flags |= BC_FLAG_S; break; } case 'w': { assert(BC_IS_BC); vm.flags |= BC_FLAG_W; break; } #endif // BC_ENABLED case 'V': case 'v': { do_exit = version = true; break; } #if DC_ENABLED case 'x': { assert(BC_IS_DC); vm.flags |= DC_FLAG_X; break; } #endif // DC_ENABLED #ifndef NDEBUG // We shouldn't get here because bc_opt_error()/bc_vm_error() should // longjmp() out. case '?': case ':': default: { abort(); } #endif // NDEBUG } } if (version) bc_vm_info(NULL); if (do_exit) exit((int) vm.status); - if (vm.exprs.len > 1 || BC_IS_DC) vm.flags |= BC_FLAG_Q; - if (opts.optind < (size_t) argc) + if (opts.optind < (size_t) argc && vm.files.v == NULL) bc_vec_init(&vm.files, sizeof(char*), NULL); for (i = opts.optind; i < (size_t) argc; ++i) bc_vec_push(&vm.files, argv + i); } Index: head/contrib/bc/src/bc/bc.c =================================================================== --- head/contrib/bc/src/bc/bc.c (revision 363809) +++ head/contrib/bc/src/bc/bc.c (revision 363810) @@ -1,57 +1,57 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The main procedure of bc. * */ #if BC_ENABLED #include #include #include #include void bc_main(int argc, char **argv) { vm.read_ret = BC_INST_RET; vm.help = bc_help; vm.sigmsg = bc_sig_msg; vm.siglen = bc_sig_msg_len; vm.next = bc_lex_token; vm.parse = bc_parse_parse; vm.expr = bc_parse_expr; - bc_vm_boot(argc, argv, "BC_LINE_LENGTH", "BC_ENV_ARGS", "BC_EXPR_EXIT"); + bc_vm_boot(argc, argv, "BC_LINE_LENGTH", "BC_ENV_ARGS"); } #endif // BC_ENABLED Index: head/contrib/bc/src/bc/parse.c =================================================================== --- head/contrib/bc/src/bc/parse.c (revision 363809) +++ head/contrib/bc/src/bc/parse.c (revision 363810) @@ -1,1532 +1,1532 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The parser for bc. * */ #if BC_ENABLED #include #include #include #include #include #include #include #include #include #include static void bc_parse_else(BcParse *p); static void bc_parse_stmt(BcParse *p); static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, BcParseNext next); static bool bc_parse_inst_isLeaf(BcInst t) { return (t >= BC_INST_NUM && t <= BC_INST_MAXSCALE) || #if BC_ENABLE_EXTRA_MATH t == BC_INST_TRUNC || #endif // BC_ENABLE_EXTRA_MATH t <= BC_INST_DEC; } static bool bc_parse_isDelimiter(const BcParse *p) { BcLexType t = p->l.t; bool good = false; if (BC_PARSE_DELIMITER(t)) return true; if (t == BC_LEX_KW_ELSE) { size_t i; uint16_t *fptr = NULL, flags = BC_PARSE_FLAG_ELSE; for (i = 0; i < p->flags.len && BC_PARSE_BLOCK_STMT(flags); ++i) { fptr = bc_vec_item_rev(&p->flags, i); flags = *fptr; if ((flags & BC_PARSE_FLAG_BRACE) && p->l.last != BC_LEX_RBRACE) return false; } good = ((flags & BC_PARSE_FLAG_IF) != 0); } else if (t == BC_LEX_RBRACE) { size_t i; for (i = 0; !good && i < p->flags.len; ++i) { uint16_t *fptr = bc_vec_item_rev(&p->flags, i); good = (((*fptr) & BC_PARSE_FLAG_BRACE) != 0); } } return good; } static void bc_parse_setLabel(BcParse *p) { BcFunc *func = p->func; BcInstPtr *ip = bc_vec_top(&p->exits); size_t *label; assert(func == bc_vec_item(&p->prog->fns, p->fidx)); label = bc_vec_item(&func->labels, ip->idx); *label = func->code.len; bc_vec_pop(&p->exits); } static void bc_parse_createLabel(BcParse *p, size_t idx) { bc_vec_push(&p->func->labels, &idx); } static void bc_parse_createCondLabel(BcParse *p, size_t idx) { bc_parse_createLabel(p, p->func->code.len); bc_vec_push(&p->conds, &idx); } static void bc_parse_createExitLabel(BcParse *p, size_t idx, bool loop) { BcInstPtr ip; assert(p->func == bc_vec_item(&p->prog->fns, p->fidx)); ip.func = loop; ip.idx = idx; ip.len = 0; bc_vec_push(&p->exits, &ip); bc_parse_createLabel(p, SIZE_MAX); } static void bc_parse_operator(BcParse *p, BcLexType type, size_t start, size_t *nexprs) { BcLexType t; uchar l, r = BC_PARSE_OP_PREC(type); uchar left = BC_PARSE_OP_LEFT(type); while (p->ops.len > start) { t = BC_PARSE_TOP_OP(p); if (t == BC_LEX_LPAREN) break; l = BC_PARSE_OP_PREC(t); if (l >= r && (l != r || !left)) break; bc_parse_push(p, BC_PARSE_TOKEN_INST(t)); bc_vec_pop(&p->ops); *nexprs -= !BC_PARSE_OP_PREFIX(t); } bc_vec_push(&p->ops, &type); } static void bc_parse_rightParen(BcParse *p, size_t *nexs) { BcLexType top; while ((top = BC_PARSE_TOP_OP(p)) != BC_LEX_LPAREN) { bc_parse_push(p, BC_PARSE_TOKEN_INST(top)); bc_vec_pop(&p->ops); *nexs -= !BC_PARSE_OP_PREFIX(top); } bc_vec_pop(&p->ops); bc_lex_next(&p->l); } static void bc_parse_params(BcParse *p, uint8_t flags) { bool comma = false; size_t nparams; bc_lex_next(&p->l); + flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); + flags |= (BC_PARSE_ARRAY | BC_PARSE_NEEDVAL); + for (nparams = 0; p->l.t != BC_LEX_RPAREN; ++nparams) { - flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); - flags |= (BC_PARSE_ARRAY | BC_PARSE_NEEDVAL); - bc_parse_expr_status(p, flags, bc_parse_next_param); comma = (p->l.t == BC_LEX_COMMA); if (comma) bc_lex_next(&p->l); } if (BC_ERR(comma)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_parse_push(p, BC_INST_CALL); bc_parse_pushIndex(p, nparams); } static void bc_parse_call(BcParse *p, const char *name, uint8_t flags) { size_t idx; bc_parse_params(p, flags); // We just assert this because bc_parse_params() should // ensure that the next token is what it should be. assert(p->l.t == BC_LEX_RPAREN); // We cannot use bc_program_insertFunc() here // because it will overwrite an existing function. idx = bc_map_index(&p->prog->fn_map, name); if (idx == BC_VEC_INVALID_IDX) { BC_SIG_LOCK; idx = bc_program_insertFunc(p->prog, name); BC_SIG_UNLOCK; assert(idx != BC_VEC_INVALID_IDX); // Make sure that this pointer was not invalidated. p->func = bc_vec_item(&p->prog->fns, p->fidx); } else idx = ((BcId*) bc_vec_item(&p->prog->fn_map, idx))->idx; bc_parse_pushIndex(p, idx); bc_lex_next(&p->l); } static void bc_parse_name(BcParse *p, BcInst *type, bool *can_assign, uint8_t flags) { char *name; BC_SIG_LOCK; name = bc_vm_strdup(p->l.str.v); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_lex_next(&p->l); if (p->l.t == BC_LEX_LBRACKET) { bc_lex_next(&p->l); if (p->l.t == BC_LEX_RBRACKET) { if (BC_ERR(!(flags & BC_PARSE_ARRAY))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); *type = BC_INST_ARRAY; *can_assign = false; } else { uint8_t flags2 = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_NEEDVAL; bc_parse_expr_status(p, flags2, bc_parse_next_elem); if (BC_ERR(p->l.t != BC_LEX_RBRACKET)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); *type = BC_INST_ARRAY_ELEM; *can_assign = true; } bc_lex_next(&p->l); bc_parse_push(p, *type); bc_parse_pushName(p, name, false); } else if (p->l.t == BC_LEX_LPAREN) { if (BC_ERR(flags & BC_PARSE_NOCALL)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); *type = BC_INST_CALL; *can_assign = false; bc_parse_call(p, name, flags); } else { *type = BC_INST_VAR; *can_assign = true; bc_parse_push(p, BC_INST_VAR); bc_parse_pushName(p, name, true); } err: BC_SIG_MAYLOCK; free(name); BC_LONGJMP_CONT; } static void bc_parse_noArgBuiltin(BcParse *p, BcInst inst) { bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); if ((p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_parse_push(p, inst); bc_lex_next(&p->l); } static void bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags, BcInst *prev) { bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); flags |= BC_PARSE_NEEDVAL; if (type == BC_LEX_KW_LENGTH) flags |= BC_PARSE_ARRAY; bc_parse_expr_status(p, flags, bc_parse_next_rel); if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); *prev = type - BC_LEX_KW_LENGTH + BC_INST_LENGTH; bc_parse_push(p, *prev); bc_lex_next(&p->l); } static void bc_parse_scale(BcParse *p, BcInst *type, bool *can_assign, uint8_t flags) { bc_lex_next(&p->l); if (p->l.t != BC_LEX_LPAREN) { *type = BC_INST_SCALE; *can_assign = true; bc_parse_push(p, BC_INST_SCALE); return; } *type = BC_INST_SCALE_FUNC; *can_assign = false; flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); flags |= BC_PARSE_NEEDVAL; bc_lex_next(&p->l); bc_parse_expr_status(p, flags, bc_parse_next_rel); if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_parse_push(p, BC_INST_SCALE_FUNC); bc_lex_next(&p->l); } static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign, size_t *nexs, uint8_t flags) { BcLexType type; uchar inst; BcInst etype = *prev; BcLexType last = p->l.last; assert(prev != NULL && can_assign != NULL); if (BC_ERR(last == BC_LEX_OP_INC || last == BC_LEX_OP_DEC || last == BC_LEX_RPAREN)) { bc_parse_err(p, BC_ERROR_PARSE_ASSIGN); } if (BC_PARSE_INST_VAR(etype)) { if (!*can_assign) bc_parse_err(p, BC_ERROR_PARSE_ASSIGN); *prev = inst = BC_INST_INC + (p->l.t != BC_LEX_OP_INC); bc_parse_push(p, inst); bc_lex_next(&p->l); *can_assign = false; } else { *prev = inst = BC_INST_ASSIGN_PLUS + (p->l.t != BC_LEX_OP_INC); bc_lex_next(&p->l); type = p->l.t; // Because we parse the next part of the expression // right here, we need to increment this. *nexs = *nexs + 1; if (type == BC_LEX_NAME) { uint8_t flags2 = flags & ~BC_PARSE_ARRAY; bc_parse_name(p, prev, can_assign, flags2 | BC_PARSE_NOCALL); } else if (type >= BC_LEX_KW_LAST && type <= BC_LEX_KW_OBASE) { bc_parse_push(p, type - BC_LEX_KW_LAST + BC_INST_LAST); bc_lex_next(&p->l); } else if (BC_NO_ERR(type == BC_LEX_KW_SCALE)) { bc_lex_next(&p->l); if (BC_ERR(p->l.t == BC_LEX_LPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); else bc_parse_push(p, BC_INST_SCALE); } else bc_parse_err(p, BC_ERROR_PARSE_TOKEN); *can_assign = false; bc_parse_push(p, BC_INST_ONE); bc_parse_push(p, inst); } } static void bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn, bool rparen, bool binlast, size_t *nexprs) { BcLexType type; bc_lex_next(&p->l); type = BC_PARSE_LEAF(*prev, binlast, rparen) ? BC_LEX_OP_MINUS : BC_LEX_NEG; *prev = BC_PARSE_TOKEN_INST(type); // We can just push onto the op stack because this is the largest // precedence operator that gets pushed. Inc/dec does not. if (type != BC_LEX_OP_MINUS) bc_vec_push(&p->ops, &type); else bc_parse_operator(p, type, ops_bgn, nexprs); } static void bc_parse_str(BcParse *p, char inst) { bc_parse_addString(p); bc_parse_push(p, inst); bc_lex_next(&p->l); } static void bc_parse_print(BcParse *p) { BcLexType t; bool comma = false; bc_lex_next(&p->l); t = p->l.t; if (bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERROR_PARSE_PRINT); do { if (t == BC_LEX_STR) bc_parse_str(p, BC_INST_PRINT_POP); else { bc_parse_expr_status(p, BC_PARSE_NEEDVAL, bc_parse_next_print); bc_parse_push(p, BC_INST_PRINT_POP); } comma = (p->l.t == BC_LEX_COMMA); if (comma) bc_lex_next(&p->l); else { if (!bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); else break; } t = p->l.t; } while (true); if (BC_ERR(comma)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); } static void bc_parse_return(BcParse *p) { BcLexType t; bool paren; uchar inst = BC_INST_RET0; if (BC_ERR(!BC_PARSE_FUNC(p))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); if (p->func->voidfn) inst = BC_INST_RET_VOID; bc_lex_next(&p->l); t = p->l.t; paren = t == BC_LEX_LPAREN; if (bc_parse_isDelimiter(p)) bc_parse_push(p, inst); else { BcParseStatus s; s = bc_parse_expr_err(p, BC_PARSE_NEEDVAL, bc_parse_next_expr); if (s == BC_PARSE_STATUS_EMPTY_EXPR) { bc_parse_push(p, inst); bc_lex_next(&p->l); } if (!paren || p->l.last != BC_LEX_RPAREN) { bc_parse_err(p, BC_ERROR_POSIX_RET); } else if (BC_ERR(p->func->voidfn)) bc_parse_verr(p, BC_ERROR_PARSE_RET_VOID, p->func->name); bc_parse_push(p, BC_INST_RET); } } +static void bc_parse_noElse(BcParse *p) { + uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p); + *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END)); + bc_parse_setLabel(p); +} + static void bc_parse_endBody(BcParse *p, bool brace) { bool has_brace, new_else = false; if (BC_ERR(p->flags.len <= 1)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); if (brace) { assert(p->l.t == BC_LEX_RBRACE); bc_lex_next(&p->l); if (BC_ERR(!bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); } has_brace = (BC_PARSE_BRACE(p) != 0); do { size_t len = p->flags.len; bool loop; if (has_brace && !brace) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); loop = (BC_PARSE_LOOP_INNER(p) != 0); if (loop || BC_PARSE_ELSE(p)) { if (loop) { size_t *label = bc_vec_top(&p->conds); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, *label); bc_vec_pop(&p->conds); } bc_parse_setLabel(p); bc_vec_pop(&p->flags); } else if (BC_PARSE_FUNC_INNER(p)) { BcInst inst = (p->func->voidfn ? BC_INST_RET_VOID : BC_INST_RET0); bc_parse_push(p, inst); bc_parse_updateFunc(p, BC_PROG_MAIN); bc_vec_pop(&p->flags); } else if (BC_PARSE_BRACE(p) && !BC_PARSE_IF(p)) bc_vec_pop(&p->flags); // This needs to be last to parse nested if's properly. if (BC_PARSE_IF(p) && (len == p->flags.len || !BC_PARSE_BRACE(p))) { while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l); bc_vec_pop(&p->flags); if (!BC_S) { *(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_IF_END; new_else = (p->l.t == BC_LEX_KW_ELSE); if (new_else) bc_parse_else(p); else if (!has_brace && (!BC_PARSE_IF_END(p) || brace)) bc_parse_noElse(p); } else bc_parse_noElse(p); } if (brace && has_brace) brace = false; } while (p->flags.len > 1 && !new_else && (!BC_PARSE_IF_END(p) || brace) && !(has_brace = (BC_PARSE_BRACE(p) != 0))); if (BC_ERR(p->flags.len == 1 && brace)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); else if (brace && BC_PARSE_BRACE(p)) { uint16_t flags = BC_PARSE_TOP_FLAG(p); if (!(flags & (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_LOOP_INNER)) && !(flags & (BC_PARSE_FLAG_IF | BC_PARSE_FLAG_ELSE)) && !(flags & (BC_PARSE_FLAG_IF_END))) { bc_vec_pop(&p->flags); } } } static void bc_parse_startBody(BcParse *p, uint16_t flags) { assert(flags); flags |= (BC_PARSE_TOP_FLAG(p) & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP)); flags |= BC_PARSE_FLAG_BODY; bc_vec_push(&p->flags, &flags); -} - -void bc_parse_noElse(BcParse *p) { - uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p); - *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END)); - bc_parse_setLabel(p); } static void bc_parse_if(BcParse *p) { size_t idx; uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL); bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); bc_parse_expr_status(p, flags, bc_parse_next_rel); if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); bc_parse_push(p, BC_INST_JUMP_ZERO); idx = p->func->labels.len; bc_parse_pushIndex(p, idx); bc_parse_createExitLabel(p, idx, false); bc_parse_startBody(p, BC_PARSE_FLAG_IF); } static void bc_parse_else(BcParse *p) { size_t idx = p->func->labels.len; if (BC_ERR(!BC_PARSE_IF_END(p))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, idx); bc_parse_noElse(p); bc_parse_createExitLabel(p, idx, false); bc_parse_startBody(p, BC_PARSE_FLAG_ELSE); bc_lex_next(&p->l); } static void bc_parse_while(BcParse *p) { size_t idx; uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL); bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); bc_parse_createCondLabel(p, p->func->labels.len); idx = p->func->labels.len; bc_parse_createExitLabel(p, idx, true); bc_parse_expr_status(p, flags, bc_parse_next_rel); if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); bc_parse_push(p, BC_INST_JUMP_ZERO); bc_parse_pushIndex(p, idx); bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER); } static void bc_parse_for(BcParse *p) { size_t cond_idx, exit_idx, body_idx, update_idx; bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); if (p->l.t != BC_LEX_SCOLON) bc_parse_expr_status(p, 0, bc_parse_next_for); else bc_parse_err(p, BC_ERROR_POSIX_FOR); if (BC_ERR(p->l.t != BC_LEX_SCOLON)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); cond_idx = p->func->labels.len; update_idx = cond_idx + 1; body_idx = update_idx + 1; exit_idx = body_idx + 1; bc_parse_createLabel(p, p->func->code.len); if (p->l.t != BC_LEX_SCOLON) { uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL); bc_parse_expr_status(p, flags, bc_parse_next_for); } else { // Set this for the next call to bc_parse_number. // This is safe to set because the current token // is a semicolon, which has no string requirement. bc_vec_string(&p->l.str, strlen(bc_parse_const1), bc_parse_const1); bc_parse_number(p); bc_parse_err(p, BC_ERROR_POSIX_FOR); } if (BC_ERR(p->l.t != BC_LEX_SCOLON)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); bc_parse_push(p, BC_INST_JUMP_ZERO); bc_parse_pushIndex(p, exit_idx); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, body_idx); bc_parse_createCondLabel(p, update_idx); if (p->l.t != BC_LEX_RPAREN) bc_parse_expr_status(p, 0, bc_parse_next_rel); else bc_parse_err(p, BC_ERROR_POSIX_FOR); if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, cond_idx); bc_parse_createLabel(p, p->func->code.len); bc_parse_createExitLabel(p, exit_idx, true); bc_lex_next(&p->l); bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER); } static void bc_parse_loopExit(BcParse *p, BcLexType type) { size_t i; BcInstPtr *ip; if (BC_ERR(!BC_PARSE_LOOP(p))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); if (type == BC_LEX_KW_BREAK) { if (BC_ERR(!p->exits.len)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); i = p->exits.len - 1; ip = bc_vec_item(&p->exits, i); while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--); assert(ip != NULL && (i < p->exits.len || ip->func)); i = ip->idx; } else i = *((size_t*) bc_vec_top(&p->conds)); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, i); bc_lex_next(&p->l); } static void bc_parse_func(BcParse *p) { bool comma = false, voidfn; uint16_t flags; size_t idx; bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERROR_PARSE_FUNC); voidfn = (!BC_IS_POSIX && p->l.t == BC_LEX_NAME && !strcmp(p->l.str.v, "void")); bc_lex_next(&p->l); voidfn = (voidfn && p->l.t == BC_LEX_NAME); if (voidfn) { bc_parse_err(p, BC_ERROR_POSIX_VOID); bc_lex_next(&p->l); } if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERROR_PARSE_FUNC); assert(p->prog->fns.len == p->prog->fn_map.len); BC_SIG_LOCK; idx = bc_program_insertFunc(p->prog, p->l.str.v); BC_SIG_UNLOCK; assert(idx); bc_parse_updateFunc(p, idx); p->func->voidfn = voidfn; bc_lex_next(&p->l); while (p->l.t != BC_LEX_RPAREN) { BcType t = BC_TYPE_VAR; if (p->l.t == BC_LEX_OP_MULTIPLY) { t = BC_TYPE_REF; bc_lex_next(&p->l); bc_parse_err(p, BC_ERROR_POSIX_REF); } if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERROR_PARSE_FUNC); p->func->nparams += 1; bc_vec_string(&p->buf, p->l.str.len, p->l.str.v); bc_lex_next(&p->l); if (p->l.t == BC_LEX_LBRACKET) { if (t == BC_TYPE_VAR) t = BC_TYPE_ARRAY; bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_RBRACKET)) bc_parse_err(p, BC_ERROR_PARSE_FUNC); bc_lex_next(&p->l); } else if (BC_ERR(t == BC_TYPE_REF)) bc_parse_verr(p, BC_ERROR_PARSE_REF_VAR, p->buf.v); comma = (p->l.t == BC_LEX_COMMA); if (comma) { bc_lex_next(&p->l); } bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line); } if (BC_ERR(comma)) bc_parse_err(p, BC_ERROR_PARSE_FUNC); flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER; bc_parse_startBody(p, flags); bc_lex_next(&p->l); if (p->l.t != BC_LEX_LBRACE) bc_parse_err(p, BC_ERROR_POSIX_BRACE); } static void bc_parse_auto(BcParse *p) { bool comma, one; if (BC_ERR(!p->auto_part)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_lex_next(&p->l); p->auto_part = comma = false; one = p->l.t == BC_LEX_NAME; while (p->l.t == BC_LEX_NAME) { BcType t; bc_vec_string(&p->buf, p->l.str.len - 1, p->l.str.v); bc_lex_next(&p->l); if (p->l.t == BC_LEX_LBRACKET) { t = BC_TYPE_ARRAY; bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_RBRACKET)) bc_parse_err(p, BC_ERROR_PARSE_FUNC); bc_lex_next(&p->l); } else t = BC_TYPE_VAR; comma = (p->l.t == BC_LEX_COMMA); if (comma) bc_lex_next(&p->l); bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line); } if (BC_ERR(comma)) bc_parse_err(p, BC_ERROR_PARSE_FUNC); if (BC_ERR(!one)) bc_parse_err(p, BC_ERROR_PARSE_NO_AUTO); if (BC_ERR(!bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); } static void bc_parse_body(BcParse *p, bool brace) { uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p); assert(flag_ptr != NULL); assert(p->flags.len >= 2); *flag_ptr &= ~(BC_PARSE_FLAG_BODY); if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) { if (BC_ERR(!brace)) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); p->auto_part = (p->l.t != BC_LEX_KW_AUTO); if (!p->auto_part) { // Make sure this is true to not get a parse error. p->auto_part = true; bc_parse_auto(p); } if (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l); } else { size_t len = p->flags.len; assert(*flag_ptr); bc_parse_stmt(p); if (!brace && !BC_PARSE_BODY(p) && len <= p->flags.len) bc_parse_endBody(p, false); } } static void bc_parse_stmt(BcParse *p) { size_t len; uint16_t flags; BcLexType type = p->l.t; if (type == BC_LEX_NLINE) { bc_lex_next(&p->l); return; } if (type == BC_LEX_KW_AUTO) { bc_parse_auto(p); return; } p->auto_part = false; if (type != BC_LEX_KW_ELSE) { if (BC_PARSE_IF_END(p)) { bc_parse_noElse(p); if (p->flags.len > 1 && !BC_PARSE_BRACE(p)) bc_parse_endBody(p, false); return; } else if (type == BC_LEX_LBRACE) { if (!BC_PARSE_BODY(p)) { bc_parse_startBody(p, BC_PARSE_FLAG_BRACE); bc_lex_next(&p->l); } else { *(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_BRACE; bc_lex_next(&p->l); bc_parse_body(p, true); } return; } else if (BC_PARSE_BODY(p) && !BC_PARSE_BRACE(p)) { bc_parse_body(p, false); return; } } len = p->flags.len; flags = BC_PARSE_TOP_FLAG(p); switch (type) { case BC_LEX_OP_INC: case BC_LEX_OP_DEC: case BC_LEX_OP_MINUS: case BC_LEX_OP_BOOL_NOT: case BC_LEX_LPAREN: case BC_LEX_NAME: case BC_LEX_NUMBER: case BC_LEX_KW_IBASE: case BC_LEX_KW_LAST: case BC_LEX_KW_LENGTH: case BC_LEX_KW_OBASE: case BC_LEX_KW_SCALE: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_SEED: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_SQRT: case BC_LEX_KW_ABS: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_IRAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_READ: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_RAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXIBASE: case BC_LEX_KW_MAXOBASE: case BC_LEX_KW_MAXSCALE: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXRAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { bc_parse_expr_status(p, BC_PARSE_PRINT, bc_parse_next_expr); break; } case BC_LEX_KW_ELSE: { bc_parse_else(p); break; } case BC_LEX_SCOLON: { // Do nothing. break; } case BC_LEX_RBRACE: { bc_parse_endBody(p, true); break; } case BC_LEX_STR: { bc_parse_str(p, BC_INST_PRINT_STR); break; } case BC_LEX_KW_BREAK: case BC_LEX_KW_CONTINUE: { bc_parse_loopExit(p, p->l.t); break; } case BC_LEX_KW_FOR: { bc_parse_for(p); break; } case BC_LEX_KW_HALT: { bc_parse_push(p, BC_INST_HALT); bc_lex_next(&p->l); break; } case BC_LEX_KW_IF: { bc_parse_if(p); break; } case BC_LEX_KW_LIMITS: { bc_vm_printf("BC_LONG_BIT = %lu\n", (ulong) BC_LONG_BIT); bc_vm_printf("BC_BASE_DIGS = %lu\n", (ulong) BC_BASE_DIGS); bc_vm_printf("BC_BASE_POW = %lu\n", (ulong) BC_BASE_POW); bc_vm_printf("BC_OVERFLOW_MAX = %lu\n", (ulong) BC_NUM_BIGDIG_MAX); bc_vm_printf("\n"); bc_vm_printf("BC_BASE_MAX = %lu\n", BC_MAX_OBASE); bc_vm_printf("BC_DIM_MAX = %lu\n", BC_MAX_DIM); bc_vm_printf("BC_SCALE_MAX = %lu\n", BC_MAX_SCALE); bc_vm_printf("BC_STRING_MAX = %lu\n", BC_MAX_STRING); bc_vm_printf("BC_NAME_MAX = %lu\n", BC_MAX_NAME); bc_vm_printf("BC_NUM_MAX = %lu\n", BC_MAX_NUM); #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_vm_printf("BC_RAND_MAX = %lu\n", BC_MAX_RAND); #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_vm_printf("MAX Exponent = %lu\n", BC_MAX_EXP); bc_vm_printf("Number of vars = %lu\n", BC_MAX_VARS); bc_lex_next(&p->l); break; } case BC_LEX_KW_PRINT: { bc_parse_print(p); break; } case BC_LEX_KW_QUIT: { // Quit is a compile-time command. We don't exit directly, // so the vm can clean up. Limits do the same thing. vm.status = BC_STATUS_QUIT; BC_VM_JMP; break; } case BC_LEX_KW_RETURN: { bc_parse_return(p); break; } case BC_LEX_KW_WHILE: { bc_parse_while(p); break; } default: { bc_parse_err(p, BC_ERROR_PARSE_TOKEN); } } if (len == p->flags.len && flags == BC_PARSE_TOP_FLAG(p)) { if (BC_ERR(!bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); } // Make sure semicolons are eaten. while (p->l.t == BC_LEX_SCOLON) bc_lex_next(&p->l); } void bc_parse_parse(BcParse *p) { assert(p); BC_SETJMP(exit); if (BC_ERR(p->l.t == BC_LEX_EOF)) bc_parse_err(p, BC_ERROR_PARSE_EOF); else if (p->l.t == BC_LEX_KW_DEFINE) { if (BC_ERR(BC_PARSE_NO_EXEC(p))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); bc_parse_func(p); } else bc_parse_stmt(p); exit: BC_SIG_MAYLOCK; if (BC_ERR(((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig))) bc_parse_reset(p); BC_LONGJMP_CONT; } static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, BcParseNext next) { BcInst prev = BC_INST_PRINT; uchar inst = BC_INST_INVALID; BcLexType top, t = p->l.t; size_t nexprs = 0, ops_bgn = p->ops.len; uint32_t i, nparens, nrelops; bool pfirst, rprn, done, get_token, assign, bin_last, incdec, can_assign; assert(!(flags & BC_PARSE_PRINT) || !(flags & BC_PARSE_NEEDVAL)); pfirst = (p->l.t == BC_LEX_LPAREN); nparens = nrelops = 0; rprn = done = get_token = assign = incdec = can_assign = false; bin_last = true; // We want to eat newlines if newlines are not a valid ending token. // This is for spacing in things like for loop headers. if (!(flags & BC_PARSE_NOREAD)) { while ((t = p->l.t) == BC_LEX_NLINE) bc_lex_next(&p->l); } for (; !done && BC_PARSE_EXPR(t); t = p->l.t) { switch (t) { case BC_LEX_OP_INC: case BC_LEX_OP_DEC: { if (BC_ERR(incdec)) bc_parse_err(p, BC_ERROR_PARSE_ASSIGN); bc_parse_incdec(p, &prev, &can_assign, &nexprs, flags); rprn = get_token = bin_last = false; incdec = true; flags &= ~(BC_PARSE_ARRAY); break; } #if BC_ENABLE_EXTRA_MATH case BC_LEX_OP_TRUNC: { if (BC_ERR(!BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_TOKEN); // I can just add the instruction because // negative will already be taken care of. bc_parse_push(p, BC_INST_TRUNC); rprn = can_assign = incdec = false; get_token = true; flags &= ~(BC_PARSE_ARRAY); break; } #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_OP_MINUS: { bc_parse_minus(p, &prev, ops_bgn, rprn, bin_last, &nexprs); rprn = get_token = can_assign = false; bin_last = (prev == BC_INST_MINUS); if (bin_last) incdec = false; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_OP_ASSIGN_POWER: case BC_LEX_OP_ASSIGN_MULTIPLY: case BC_LEX_OP_ASSIGN_DIVIDE: case BC_LEX_OP_ASSIGN_MODULUS: case BC_LEX_OP_ASSIGN_PLUS: case BC_LEX_OP_ASSIGN_MINUS: #if BC_ENABLE_EXTRA_MATH case BC_LEX_OP_ASSIGN_PLACES: case BC_LEX_OP_ASSIGN_LSHIFT: case BC_LEX_OP_ASSIGN_RSHIFT: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_OP_ASSIGN: { if (!BC_PARSE_INST_VAR(prev)) bc_parse_err(p, BC_ERROR_PARSE_ASSIGN); } // Fallthrough. case BC_LEX_OP_POWER: case BC_LEX_OP_MULTIPLY: case BC_LEX_OP_DIVIDE: case BC_LEX_OP_MODULUS: case BC_LEX_OP_PLUS: #if BC_ENABLE_EXTRA_MATH case BC_LEX_OP_PLACES: case BC_LEX_OP_LSHIFT: case BC_LEX_OP_RSHIFT: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_OP_REL_EQ: case BC_LEX_OP_REL_LE: case BC_LEX_OP_REL_GE: case BC_LEX_OP_REL_NE: case BC_LEX_OP_REL_LT: case BC_LEX_OP_REL_GT: case BC_LEX_OP_BOOL_NOT: case BC_LEX_OP_BOOL_OR: case BC_LEX_OP_BOOL_AND: { if (BC_PARSE_OP_PREFIX(t)) { if (BC_ERR(!bin_last && !BC_PARSE_OP_PREFIX(p->l.last))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); } else if (BC_ERR(BC_PARSE_PREV_PREFIX(prev) || bin_last)) bc_parse_err(p, BC_ERROR_PARSE_EXPR); nrelops += (t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT); prev = BC_PARSE_TOKEN_INST(t); bc_parse_operator(p, t, ops_bgn, &nexprs); rprn = incdec = can_assign = false; get_token = true; bin_last = !BC_PARSE_OP_PREFIX(t); flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_LPAREN: { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); nparens += 1; rprn = incdec = can_assign = false; get_token = true; bc_vec_push(&p->ops, &t); break; } case BC_LEX_RPAREN: { // This needs to be a status. The error // is handled in bc_parse_expr_status(). if (BC_ERR(p->l.last == BC_LEX_LPAREN)) return BC_PARSE_STATUS_EMPTY_EXPR; if (BC_ERR(bin_last || BC_PARSE_PREV_PREFIX(prev))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); if (!nparens) { done = true; get_token = false; break; } nparens -= 1; rprn = true; get_token = bin_last = incdec = false; bc_parse_rightParen(p, &nexprs); break; } case BC_LEX_NAME: { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); get_token = bin_last = false; bc_parse_name(p, &prev, &can_assign, flags & ~BC_PARSE_NOCALL); rprn = (prev == BC_INST_CALL); nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_NUMBER: { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); bc_parse_number(p); nexprs += 1; prev = BC_INST_NUM; get_token = true; rprn = bin_last = can_assign = false; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_IBASE: case BC_LEX_KW_LAST: case BC_LEX_KW_OBASE: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_SEED: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); prev = t - BC_LEX_KW_LAST + BC_INST_LAST; bc_parse_push(p, prev); get_token = can_assign = true; rprn = bin_last = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_LENGTH: case BC_LEX_KW_SQRT: case BC_LEX_KW_ABS: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_IRAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); bc_parse_builtin(p, t, flags, &prev); rprn = get_token = bin_last = incdec = can_assign = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_READ: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_RAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXIBASE: case BC_LEX_KW_MAXOBASE: case BC_LEX_KW_MAXSCALE: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_LEX_KW_MAXRAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); else if (t == BC_LEX_KW_READ && BC_ERR(flags & BC_PARSE_NOREAD)) bc_parse_err(p, BC_ERROR_EXEC_REC_READ); else { prev = t - BC_LEX_KW_READ + BC_INST_READ; bc_parse_noArgBuiltin(p, prev); } rprn = get_token = bin_last = incdec = can_assign = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_SCALE: { if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); bc_parse_scale(p, &prev, &can_assign, flags); rprn = get_token = bin_last = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } default: { #ifndef NDEBUG bc_parse_err(p, BC_ERROR_PARSE_TOKEN); break; #endif // NDEBUG } } if (get_token) bc_lex_next(&p->l); } while (p->ops.len > ops_bgn) { top = BC_PARSE_TOP_OP(p); assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN; if (BC_ERR(top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)) bc_parse_err(p, BC_ERROR_PARSE_EXPR); bc_parse_push(p, BC_PARSE_TOKEN_INST(top)); nexprs -= !BC_PARSE_OP_PREFIX(top); bc_vec_pop(&p->ops); incdec = false; } if (BC_ERR(nexprs != 1)) bc_parse_err(p, BC_ERROR_PARSE_EXPR); for (i = 0; i < next.len && t != next.tokens[i]; ++i); if (BC_ERR(i == next.len && !bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERROR_PARSE_EXPR); if (!(flags & BC_PARSE_REL) && nrelops) bc_parse_err(p, BC_ERROR_POSIX_REL_POS); else if ((flags & BC_PARSE_REL) && nrelops > 1) bc_parse_err(p, BC_ERROR_POSIX_MULTIREL); if (!(flags & BC_PARSE_NEEDVAL) && !pfirst) { if (assign) { inst = *((uchar*) bc_vec_top(&p->func->code)); inst += (BC_INST_ASSIGN_POWER_NO_VAL - BC_INST_ASSIGN_POWER); incdec = false; } else if (incdec && !(flags & BC_PARSE_PRINT)) { inst = *((uchar*) bc_vec_top(&p->func->code)); incdec = (inst <= BC_INST_DEC); inst = BC_INST_ASSIGN_PLUS_NO_VAL + (inst != BC_INST_INC && inst != BC_INST_ASSIGN_PLUS); } if (inst >= BC_INST_ASSIGN_POWER_NO_VAL && inst <= BC_INST_ASSIGN_NO_VAL) { bc_vec_pop(&p->func->code); if (incdec) bc_parse_push(p, BC_INST_ONE); bc_parse_push(p, inst); } } if ((flags & BC_PARSE_PRINT)) { if (pfirst || !assign) bc_parse_push(p, BC_INST_PRINT); } else if (!(flags & BC_PARSE_NEEDVAL) && (inst < BC_INST_ASSIGN_POWER_NO_VAL || inst > BC_INST_ASSIGN_NO_VAL)) { bc_parse_push(p, BC_INST_POP); } // We want to eat newlines if newlines are not a valid ending token. // This is for spacing in things like for loop headers. for (incdec = true, i = 0; i < next.len && incdec; ++i) incdec = (next.tokens[i] != BC_LEX_NLINE); if (incdec) { while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l); } return BC_PARSE_STATUS_SUCCESS; } void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next) { BcParseStatus s = bc_parse_expr_err(p, flags, next); if (BC_ERR(s == BC_PARSE_STATUS_EMPTY_EXPR)) bc_parse_err(p, BC_ERROR_PARSE_EMPTY_EXPR); } void bc_parse_expr(BcParse *p, uint8_t flags) { assert(p); bc_parse_expr_status(p, flags, bc_parse_next_read); } #endif // BC_ENABLED Index: head/contrib/bc/src/dc/dc.c =================================================================== --- head/contrib/bc/src/dc/dc.c (revision 363809) +++ head/contrib/bc/src/dc/dc.c (revision 363810) @@ -1,57 +1,57 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The main procedure of dc. * */ #if DC_ENABLED #include #include #include #include void dc_main(int argc, char **argv) { vm.read_ret = BC_INST_POP_EXEC; vm.help = dc_help; vm.sigmsg = dc_sig_msg; vm.siglen = dc_sig_msg_len; vm.next = dc_lex_token; vm.parse = dc_parse_parse; vm.expr = dc_parse_expr; - bc_vm_boot(argc, argv, "DC_LINE_LENGTH", "DC_ENV_ARGS", "DC_EXPR_EXIT"); + bc_vm_boot(argc, argv, "DC_LINE_LENGTH", "DC_ENV_ARGS"); } #endif // DC_ENABLED Index: head/contrib/bc/src/vm.c =================================================================== --- head/contrib/bc/src/vm.c (revision 363809) +++ head/contrib/bc/src/vm.c (revision 363810) @@ -1,871 +1,861 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Code common to all of bc and dc. * */ #include #include #include #include #include #include #include #ifndef _WIN32 #include #include #else // _WIN32 #define WIN32_LEAN_AND_MEAN #include #include #endif // _WIN32 #include #include #include #include #include #include #if BC_DEBUG_CODE BC_NORETURN void bc_vm_jmp(const char* f) { #else // BC_DEBUG_CODE BC_NORETURN void bc_vm_jmp(void) { #endif assert(BC_SIG_EXC); BC_SIG_MAYLOCK; #if BC_DEBUG_CODE bc_file_puts(&vm.ferr, "Longjmp: "); bc_file_puts(&vm.ferr, f); bc_file_putchar(&vm.ferr, '\n'); bc_file_flush(&vm.ferr); #endif // BC_DEBUG_CODE #ifndef NDEBUG assert(vm.jmp_bufs.len - (size_t) vm.sig_pop); #endif // NDEBUG if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); else vm.sig_pop = 1; siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1); } static void bc_vm_sig(int sig) { // There is already a signal in flight. if (vm.status == (sig_atomic_t) BC_STATUS_QUIT || vm.sig) { if (!BC_TTY || sig != SIGINT) vm.status = BC_STATUS_QUIT; return; } if (BC_TTY && sig == SIGINT) { int err = errno; if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen) vm.status = BC_STATUS_ERROR_FATAL; else vm.sig = 1; errno = err; } else vm.status = BC_STATUS_QUIT; assert(vm.jmp_bufs.len); if (!vm.sig_lock) BC_VM_JMP; } void bc_vm_info(const char* const help) { BC_SIG_ASSERT_LOCKED; bc_file_puts(&vm.fout, vm.name); bc_file_putchar(&vm.fout, ' '); bc_file_puts(&vm.fout, BC_VERSION); bc_file_putchar(&vm.fout, '\n'); bc_file_puts(&vm.fout, bc_copyright); if (help) { bc_file_putchar(&vm.fout, '\n'); bc_file_printf(&vm.fout, help, vm.name, vm.name); } bc_file_flush(&vm.fout); } void bc_vm_error(BcError e, size_t line, ...) { BcStatus s; va_list args; uchar id = bc_err_ids[e]; const char* err_type = vm.err_ids[id]; sig_atomic_t lock; assert(e < BC_ERROR_NELEMS); assert(!vm.sig_pop); #if BC_ENABLED if (!BC_S && e >= BC_ERROR_POSIX_START) { if (BC_W) { // Make sure to not return an error. id = UCHAR_MAX; err_type = vm.err_ids[BC_ERR_IDX_WARN]; } else return; } #endif // BC_ENABLED BC_SIG_TRYLOCK(lock); // Make sure all of stdout is written first. s = bc_file_flushErr(&vm.fout); if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) { vm.status = (sig_atomic_t) s; BC_VM_JMP; } va_start(args, line); bc_file_putchar(&vm.ferr, '\n'); bc_file_puts(&vm.ferr, err_type); bc_file_putchar(&vm.ferr, ' '); bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args); va_end(args); if (BC_NO_ERR(vm.file)) { // This is the condition for parsing vs runtime. // If line is not 0, it is parsing. if (line) { bc_file_puts(&vm.ferr, "\n "); bc_file_puts(&vm.ferr, vm.file); bc_file_printf(&vm.ferr, bc_err_line, line); } else { BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0); BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func); bc_file_puts(&vm.ferr, "\n "); bc_file_puts(&vm.ferr, vm.func_header); bc_file_putchar(&vm.ferr, ' '); bc_file_puts(&vm.ferr, f->name); #if BC_ENABLED if (BC_IS_BC && ip->func != BC_PROG_MAIN && ip->func != BC_PROG_READ) { bc_file_puts(&vm.ferr, "()"); } #endif // BC_ENABLED } } bc_file_puts(&vm.ferr, "\n\n"); s = bc_file_flushErr(&vm.ferr); vm.status = s == BC_STATUS_ERROR_FATAL ? (sig_atomic_t) s : (sig_atomic_t) (uchar) (id + 1); if (BC_ERR(vm.status)) BC_VM_JMP; BC_SIG_TRYUNLOCK(lock); } static void bc_vm_envArgs(const char* const env_args_name) { char *env_args = getenv(env_args_name), *buf, *start; char instr = '\0'; BC_SIG_ASSERT_LOCKED; if (env_args == NULL) return; start = buf = vm.env_args_buffer = bc_vm_strdup(env_args); assert(buf != NULL); bc_vec_init(&vm.env_args, sizeof(char*), NULL); bc_vec_push(&vm.env_args, &env_args_name); while (*buf) { if (!isspace(*buf)) { if (*buf == '"' || *buf == '\'') { instr = *buf; buf += 1; if (*buf == instr) { instr = '\0'; buf += 1; continue; } } bc_vec_push(&vm.env_args, &buf); while (*buf && ((!instr && !isspace(*buf)) || (instr && *buf != instr))) { buf += 1; } if (*buf) { if (instr) instr = '\0'; *buf = '\0'; buf += 1; start = buf; } else if (instr) bc_vm_error(BC_ERROR_FATAL_OPTION, 0, start); } else buf += 1; } // Make sure to push a NULL pointer at the end. buf = NULL; bc_vec_push(&vm.env_args, &buf); bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0)); } static size_t bc_vm_envLen(const char *var) { char *lenv = getenv(var); size_t i, len = BC_NUM_PRINT_WIDTH; int num; if (lenv == NULL) return len; len = strlen(lenv); for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]); if (num) { len = (size_t) atoi(lenv) - 1; if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH; } else len = BC_NUM_PRINT_WIDTH; return len; } void bc_vm_shutdown(void) { BC_SIG_ASSERT_LOCKED; #if BC_ENABLE_NLS if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog); #endif // BC_ENABLE_NLS #if BC_ENABLE_HISTORY // This must always run to ensure that the terminal is back to normal. if (BC_TTY) bc_history_free(&vm.history); #endif // BC_ENABLE_HISTORY #ifndef NDEBUG bc_vec_free(&vm.env_args); free(vm.env_args_buffer); bc_vec_free(&vm.files); bc_vec_free(&vm.exprs); bc_program_free(&vm.prog); bc_parse_free(&vm.prs); { size_t i; for (i = 0; i < vm.temps.len; ++i) free(((BcNum*) bc_vec_item(&vm.temps, i))->num); bc_vec_free(&vm.temps); } #endif // NDEBUG bc_file_free(&vm.fout); bc_file_free(&vm.ferr); } inline size_t bc_vm_arraySize(size_t n, size_t size) { size_t res = n * size; if (BC_ERR(res >= SIZE_MAX || (n != 0 && res / n != size))) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return res; } inline size_t bc_vm_growSize(size_t a, size_t b) { size_t res = a + b; if (BC_ERR(res >= SIZE_MAX || res < a || res < b)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return res; } void* bc_vm_malloc(size_t n) { void* ptr; BC_SIG_ASSERT_LOCKED; ptr = malloc(n); if (BC_ERR(ptr == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return ptr; } void* bc_vm_realloc(void *ptr, size_t n) { void* temp; BC_SIG_ASSERT_LOCKED; temp = realloc(ptr, n); if (BC_ERR(temp == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return temp; } char* bc_vm_strdup(const char *str) { char *s; BC_SIG_ASSERT_LOCKED; s = strdup(str); if (BC_ERR(!s)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return s; } void bc_vm_printf(const char *fmt, ...) { va_list args; BC_SIG_LOCK; va_start(args, fmt); bc_file_vprintf(&vm.fout, fmt, args); va_end(args); vm.nchars = 0; BC_SIG_UNLOCK; } void bc_vm_putchar(int c) { bc_file_putchar(&vm.fout, (uchar) c); vm.nchars = (c == '\n' ? 0 : vm.nchars + 1); } static void bc_vm_clean(void) { BcVec *fns = &vm.prog.fns; BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN); BcInstPtr *ip = bc_vec_item(&vm.prog.stack, 0); bool good = ((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig); if (good) bc_program_reset(&vm.prog); #if BC_ENABLED if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs); #endif // BC_ENABLED #if DC_ENABLED if (BC_IS_DC) { size_t i; good = true; for (i = 0; good && i < vm.prog.results.len; ++i) { BcResult *r = (BcResult*) bc_vec_item(&vm.prog.results, i); good = BC_VM_SAFE_RESULT(r); } } #endif // DC_ENABLED // If this condition is true, we can get rid of strings, // constants, and code. This is an idea from busybox. if (good && vm.prog.stack.len == 1 && ip->idx == f->code.len) { #if BC_ENABLED if (BC_IS_BC) { bc_vec_npop(&f->labels, f->labels.len); bc_vec_npop(&f->strs, f->strs.len); bc_vec_npop(&f->consts, f->consts.len); } #endif // BC_ENABLED #if DC_ENABLED // Note to self: you cannot delete strings and functions. Deal with it. if (BC_IS_DC) bc_vec_npop(vm.prog.consts, vm.prog.consts->len); #endif // DC_ENABLED bc_vec_npop(&f->code, f->code.len); ip->idx = 0; } } -static void bc_vm_process(const char *text, bool is_stdin) { +static void bc_vm_process(const char *text) { bc_parse_text(&vm.prs, text); do { #if BC_ENABLED if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs); #endif // BC_ENABLED while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs); -#if BC_ENABLED - if (BC_IS_BC) { - - uint16_t *flags = BC_PARSE_TOP_FLAG_PTR(&vm.prs); - - if (!is_stdin && vm.prs.flags.len == 1 && - *flags == BC_PARSE_FLAG_IF_END) - { - bc_parse_noElse(&vm.prs); - } - - if (BC_PARSE_NO_EXEC(&vm.prs)) return; - } -#endif // BC_ENABLED - bc_program_exec(&vm.prog); assert(BC_IS_DC || vm.prog.results.len == 0); if (BC_I) bc_file_flush(&vm.fout); } while (vm.prs.l.t != BC_LEX_EOF); } +#if BC_ENABLED +static void bc_vm_endif(void) { + + size_t i; + bool good; + + if (BC_NO_ERR(!BC_PARSE_NO_EXEC(&vm.prs))) return; + + good = true; + + for (i = 0; good && i < vm.prs.flags.len; ++i) { + uint16_t flag = *((uint16_t*) bc_vec_item(&vm.prs.flags, i)); + good = ((flag & BC_PARSE_FLAG_BRACE) != BC_PARSE_FLAG_BRACE); + } + + if (good) { + while (BC_PARSE_IF_END(&vm.prs)) bc_vm_process("else {}"); + } + else bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK); +} +#endif // BC_ENABLED + static void bc_vm_file(const char *file) { char *data = NULL; assert(!vm.sig_pop); bc_lex_file(&vm.prs.l, file); BC_SIG_LOCK; bc_read_file(file, &data); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; - bc_vm_process(data, false); + bc_vm_process(data); #if BC_ENABLED - if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs))) - bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK); + if (BC_IS_BC) bc_vm_endif(); #endif // BC_ENABLED err: BC_SIG_MAYLOCK; free(data); bc_vm_clean(); // bc_program_reset(), called by bc_vm_clean(), resets the status. // We want it to clear the sig_pop variable in case it was set. if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP; BC_LONGJMP_CONT; } static void bc_vm_stdin(void) { BcStatus s; BcVec buf, buffer; size_t string = 0; bool comment = false, hash = false; bc_lex_file(&vm.prs.l, bc_program_stdin_name); BC_SIG_LOCK; bc_vec_init(&buffer, sizeof(uchar), NULL); bc_vec_init(&buf, sizeof(uchar), NULL); bc_vec_pushByte(&buffer, '\0'); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; restart: // This loop is complex because the vm tries not to send any lines that end // with a backslash to the parser. The reason for that is because the parser // treats a backslash+newline combo as whitespace, per the bc spec. In that // case, and for strings and comments, the parser will expect more stuff. while ((!(s = bc_read_line(&buf, ">>> ")) || (vm.eof = (s == BC_STATUS_EOF))) && buf.len > 1) { char c2, *str = buf.v; size_t i, len = buf.len - 1; for (i = 0; i < len; ++i) { bool notend = len > i + 1; uchar c = (uchar) str[i]; hash = (!comment && !string && ((hash && c != '\n') || (!hash && c == '#'))); if (!hash && !comment && (i - 1 > len || str[i - 1] != '\\')) { if (BC_IS_BC) string ^= (c == '"'); else if (c == ']') string -= 1; else if (c == '[') string += 1; } if (BC_IS_BC && !hash && !string && notend) { c2 = str[i + 1]; if (c == '/' && !comment && c2 == '*') { comment = true; i += 1; } else if (c == '*' && comment && c2 == '/') { comment = false; i += 1; } } } bc_vec_concat(&buffer, buf.v); if (string || comment) continue; if (len >= 2 && str[len - 2] == '\\' && str[len - 1] == '\n') continue; #if BC_ENABLE_HISTORY if (vm.history.stdin_has_data) continue; #endif // BC_ENABLE_HISTORY - bc_vm_process(buffer.v, true); + bc_vm_process(buffer.v); bc_vec_empty(&buffer); if (vm.eof) break; else bc_vm_clean(); } if (!BC_STATUS_IS_ERROR(s)) { if (BC_ERR(comment)) bc_parse_err(&vm.prs, BC_ERROR_PARSE_COMMENT); else if (BC_ERR(string)) bc_parse_err(&vm.prs, BC_ERROR_PARSE_STRING); #if BC_ENABLED - else if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs))) { - - size_t i; - bool good = true; - - for (i = 0; good && i < vm.prs.flags.len; ++i) { - uint16_t flag = *((uint16_t*) bc_vec_item(&vm.prs.flags, i)); - good = ((flag & BC_PARSE_FLAG_BRACE) != BC_PARSE_FLAG_BRACE); - } - - if (good) { - while (BC_PARSE_IF_END(&vm.prs)) bc_vm_process("else {}", true); - } - else bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK); - } + else if (BC_IS_BC) bc_vm_endif(); #endif // BC_ENABLED } err: BC_SIG_MAYLOCK; bc_vm_clean(); vm.status = vm.status == BC_STATUS_ERROR_FATAL || vm.status == BC_STATUS_QUIT || !BC_I ? vm.status : BC_STATUS_SUCCESS; if (!vm.status && !vm.eof) { bc_vec_empty(&buffer); BC_LONGJMP_STOP; BC_SIG_UNLOCK; goto restart; } bc_vec_free(&buf); bc_vec_free(&buffer); BC_LONGJMP_CONT; } #if BC_ENABLED static void bc_vm_load(const char *name, const char *text) { bc_lex_file(&vm.prs.l, name); bc_parse_text(&vm.prs, text); while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs); } #endif // BC_ENABLED static void bc_vm_defaultMsgs(void) { size_t i; vm.func_header = bc_err_func_header; for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i) vm.err_ids[i] = bc_errs[i]; for (i = 0; i < BC_ERROR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i]; } static void bc_vm_gettext(void) { #if BC_ENABLE_NLS uchar id = 0; int set = 1, msg = 1; size_t i; if (vm.locale == NULL) { vm.catalog = BC_VM_INVALID_CATALOG; bc_vm_defaultMsgs(); return; } vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE); if (vm.catalog == BC_VM_INVALID_CATALOG) { bc_vm_defaultMsgs(); return; } vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header); for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg) vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]); i = 0; id = bc_err_ids[i]; for (set = id + 3, msg = 1; i < BC_ERROR_NELEMS; ++i, ++msg) { if (id != bc_err_ids[i]) { msg = 1; id = bc_err_ids[i]; set = id + 3; } vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]); } #else // BC_ENABLE_NLS bc_vm_defaultMsgs(); #endif // BC_ENABLE_NLS } -static void bc_vm_exec(const char* env_exp_exit) { +static void bc_vm_exec(void) { size_t i; bool has_file = false; BcVec buf; #if BC_ENABLED if (BC_IS_BC && (vm.flags & BC_FLAG_L)) { bc_vm_load(bc_lib_name, bc_lib); #if BC_ENABLE_EXTRA_MATH if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2); #endif // BC_ENABLE_EXTRA_MATH } #endif // BC_ENABLED if (vm.exprs.len) { size_t len = vm.exprs.len - 1; bool more; BC_SIG_LOCK; bc_vec_init(&buf, sizeof(uchar), NULL); #ifndef NDEBUG BC_SETJMP_LOCKED(err); #endif // NDEBUG BC_SIG_UNLOCK; bc_lex_file(&vm.prs.l, bc_program_exprs_name); do { more = bc_read_buf(&buf, vm.exprs.v, &len); bc_vec_pushByte(&buf, '\0'); - bc_vm_process(buf.v, false); + bc_vm_process(buf.v); bc_vec_npop(&buf, buf.len); } while (more); BC_SIG_LOCK; bc_vec_free(&buf); #ifndef NDEBUG BC_UNSETJMP; #endif // NDEBUG BC_SIG_UNLOCK; - if (getenv(env_exp_exit) != NULL) return; + if (!vm.no_exit_exprs) return; } for (i = 0; i < vm.files.len; ++i) { char *path = *((char**) bc_vec_item(&vm.files, i)); if (!strcmp(path, "")) continue; has_file = true; bc_vm_file(path); } if (BC_IS_BC || !has_file) bc_vm_stdin(); // These are all protected by ifndef NDEBUG because if these are needed, bc is // goingi to exit anyway, and I see no reason to include this code in a release // build when the OS is going to free all of the resources anyway. #ifndef NDEBUG return; err: BC_SIG_MAYLOCK; bc_vec_free(&buf); BC_LONGJMP_CONT; #endif // NDEBUG } void bc_vm_boot(int argc, char *argv[], const char *env_len, - const char* const env_args, const char* env_exp_exit) + const char* const env_args) { int ttyin, ttyout, ttyerr; struct sigaction sa; BC_SIG_ASSERT_LOCKED; ttyin = isatty(STDIN_FILENO); ttyout = isatty(STDOUT_FILENO); ttyerr = isatty(STDERR_FILENO); vm.flags |= ttyin ? BC_FLAG_TTYIN : 0; vm.flags |= (ttyin != 0 && ttyout != 0 && ttyerr != 0) ? BC_FLAG_TTY : 0; vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0; sigemptyset(&sa.sa_mask); sa.sa_handler = bc_vm_sig; sa.sa_flags = SA_NODEFER; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); #if BC_ENABLE_HISTORY if (BC_TTY) sigaction(SIGHUP, &sa, NULL); #endif // BC_ENABLE_HISTORY memcpy(vm.max_num, bc_num_bigdigMax, bc_num_bigdigMax_size * sizeof(BcDig)); bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10); vm.max.len = bc_num_bigdigMax_size; vm.file = NULL; bc_vm_gettext(); bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE, BC_VM_STDERR_BUF_SIZE); bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE); vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE; vm.line_len = (uint16_t) bc_vm_envLen(env_len); bc_vec_clear(&vm.files); bc_vec_clear(&vm.exprs); bc_vec_init(&vm.temps, sizeof(BcNum), NULL); bc_program_init(&vm.prog); bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN); #if BC_ENABLE_HISTORY if (BC_TTY) bc_history_init(&vm.history); #endif // BC_ENABLE_HISTORY #if BC_ENABLED if (BC_IS_BC) vm.flags |= BC_FLAG_S * (getenv("POSIXLY_CORRECT") != NULL); #endif // BC_ENABLED bc_vm_envArgs(env_args); bc_args(argc, argv); #if BC_ENABLED if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G); #endif // BC_ENABLED vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE; vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE; vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE; #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1; #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #if BC_ENABLED if (BC_IS_BC && !BC_IS_POSIX) vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE; #endif // BC_ENABLED - if (BC_IS_BC && BC_I && !(vm.flags & BC_FLAG_Q)) bc_vm_info(NULL); - BC_SIG_UNLOCK; - bc_vm_exec(env_exp_exit); + bc_vm_exec(); } Index: head/contrib/bc/tests/bc/all.txt =================================================================== --- head/contrib/bc/tests/bc/all.txt (revision 363809) +++ head/contrib/bc/tests/bc/all.txt (revision 363810) @@ -1,44 +1,46 @@ decimal length scale shift add subtract multiply divide modulus power sqrt trunc places vars boolean comp abs assignments functions scientific engineering globals strings letters print print2 parse exponent log pi arctangent sine cosine bessel arrays misc misc1 misc2 misc3 misc4 misc5 +misc6 +misc7 void rand lib2 Index: head/contrib/bc/tests/bc/misc6.txt =================================================================== --- head/contrib/bc/tests/bc/misc6.txt (nonexistent) +++ head/contrib/bc/tests/bc/misc6.txt (revision 363810) @@ -0,0 +1 @@ +link stdin1.txt \ No newline at end of file Property changes on: head/contrib/bc/tests/bc/misc6.txt ___________________________________________________________________ Added: svn:special ## -0,0 +1 ## +* \ No newline at end of property Index: head/contrib/bc/tests/bc/misc6_results.txt =================================================================== --- head/contrib/bc/tests/bc/misc6_results.txt (nonexistent) +++ head/contrib/bc/tests/bc/misc6_results.txt (revision 363810) @@ -0,0 +1 @@ +link stdin1_results.txt \ No newline at end of file Property changes on: head/contrib/bc/tests/bc/misc6_results.txt ___________________________________________________________________ Added: svn:special ## -0,0 +1 ## +* \ No newline at end of property Index: head/contrib/bc/tests/bc/misc7.txt =================================================================== --- head/contrib/bc/tests/bc/misc7.txt (nonexistent) +++ head/contrib/bc/tests/bc/misc7.txt (revision 363810) @@ -0,0 +1 @@ +link stdin2.txt \ No newline at end of file Property changes on: head/contrib/bc/tests/bc/misc7.txt ___________________________________________________________________ Added: svn:special ## -0,0 +1 ## +* \ No newline at end of property Index: head/contrib/bc/tests/bc/misc7_results.txt =================================================================== --- head/contrib/bc/tests/bc/misc7_results.txt (nonexistent) +++ head/contrib/bc/tests/bc/misc7_results.txt (revision 363810) @@ -0,0 +1 @@ +link stdin2_results.txt \ No newline at end of file Property changes on: head/contrib/bc/tests/bc/misc7_results.txt ___________________________________________________________________ Added: svn:special ## -0,0 +1 ## +* \ No newline at end of property Index: head/contrib/bc/tests/bc/stdin1.txt =================================================================== --- head/contrib/bc/tests/bc/stdin1.txt (nonexistent) +++ head/contrib/bc/tests/bc/stdin1.txt (revision 363810) @@ -0,0 +1,2 @@ +if (1 < 3) + if (2 < 3) 1 Property changes on: head/contrib/bc/tests/bc/stdin1.txt ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: head/contrib/bc/tests/bc/stdin1_results.txt =================================================================== --- head/contrib/bc/tests/bc/stdin1_results.txt (nonexistent) +++ head/contrib/bc/tests/bc/stdin1_results.txt (revision 363810) @@ -0,0 +1 @@ +1 Property changes on: head/contrib/bc/tests/bc/stdin1_results.txt ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: head/contrib/bc/tests/bc/stdin2.txt =================================================================== --- head/contrib/bc/tests/bc/stdin2.txt (nonexistent) +++ head/contrib/bc/tests/bc/stdin2.txt (revision 363810) @@ -0,0 +1 @@ +for (i = 0; i < 3; ++i) if (2 < 3) 1 Property changes on: head/contrib/bc/tests/bc/stdin2.txt ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: head/contrib/bc/tests/bc/stdin2_results.txt =================================================================== --- head/contrib/bc/tests/bc/stdin2_results.txt (nonexistent) +++ head/contrib/bc/tests/bc/stdin2_results.txt (revision 363810) @@ -0,0 +1,3 @@ +1 +1 +1 Property changes on: head/contrib/bc/tests/bc/stdin2_results.txt ___________________________________________________________________ Added: svn:eol-style ## -0,0 +1 ## +native \ No newline at end of property Added: svn:keywords ## -0,0 +1 ## +FreeBSD=%H \ No newline at end of property Added: svn:mime-type ## -0,0 +1 ## +text/plain \ No newline at end of property Index: head/contrib/bc =================================================================== --- head/contrib/bc (revision 363809) +++ head/contrib/bc (revision 363810) Property changes on: head/contrib/bc ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,1 ## Merged /vendor/bc/dist:r363091-363808