diff --git a/contrib/bc/Makefile.in b/contrib/bc/Makefile.in index dbb5debd44cc..db8e24967996 100644 --- a/contrib/bc/Makefile.in +++ b/contrib/bc/Makefile.in @@ -1,445 +1,445 @@ # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2021 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.3.0 +VERSION = 3.3.3 SRC = %%SRC%% OBJ = %%OBJ%% GCDA = %%GCDA%% GCNO = %%GCNO%% BC_ENABLED_NAME = BC_ENABLED BC_ENABLED = %%BC_ENABLED%% DC_ENABLED_NAME = DC_ENABLED DC_ENABLED = %%DC_ENABLED%% HEADERS = include/args.h include/file.h include/lang.h include/lex.h include/num.h include/opt.h include/parse.h include/program.h include/read.h include/status.h include/vector.h include/vm.h BC_HEADERS = include/bc.h DC_HEADERS = include/dc.h HISTORY_HEADERS = include/history.h EXTRA_MATH_HEADERS = include/rand.h LIBRARY_HEADERS = include/bcl.h include/library.h 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) BC_TEST_OUTPUTS = tests/bc_outputs BC_FUZZ_OUTPUTS = tests/fuzzing/bc_outputs1 tests/fuzzing/bc_outputs2 tests/fuzzing/bc_outputs3 DC_TEST_OUTPUTS = tests/dc_outputs DC_FUZZ_OUTPUTS = tests/fuzzing/dc_outputs LIB = libbcl LIB_NAME = $(LIB).a LIBBC = $(BIN)/$(LIB_NAME) BCL = bcl BCL_TEST = $(BIN)/$(BCL) BCL_TEST_C = tests/$(BCL).c 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 BCL_MANPAGE_NAME = bcl.3 BCL_MANPAGE = $(MANUALS)/$(BCL_MANPAGE_NAME) BCL_MD = $(BCL_MANPAGE).md MANPAGE_INSTALL_ARGS = -Dm644 BINARY_INSTALL_ARGS = -Dm755 BCL_HEADER_NAME = bcl.h BCL_HEADER = include/$(BCL_HEADER_NAME) %%DESTDIR%% BINDIR = %%BINDIR%% INCLUDEDIR = %%INCLUDEDIR%% LIBDIR = %%LIBDIR%% MAN1DIR = %%MAN1DIR%% MAN3DIR = %%MAN3DIR%% MAIN_EXEC = $(EXEC_PREFIX)$(%%MAIN_EXEC%%)$(EXEC_SUFFIX) EXEC = $(%%EXEC%%) NLSPATH = %%NLSPATH%% BC_ENABLE_LIBRARY = %%LIBRARY%% 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%% BC_ENABLE_AFL = %%FUZZ%% BC_ENABLE_MEMCHECK = %%MEMCHECK%% RM = rm MKDIR = mkdir INSTALL = ./exec-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 TEST_STARS = "***********************************************************************" 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) CPPFLAGS8 = $(CPPFLAGS7) -DBC_ENABLE_HISTORY=$(BC_ENABLE_HISTORY) -DBC_ENABLE_LIBRARY=$(BC_ENABLE_LIBRARY) CPPFLAGS = $(CPPFLAGS8) -DBC_ENABLE_MEMCHECK=$(BC_ENABLE_MEMCHECK) -DBC_ENABLE_AFL=$(BC_ENABLE_AFL) CFLAGS = $(CPPFLAGS) %%CPPFLAGS%% %%CFLAGS%% LDFLAGS = %%LDFLAGS%% HOSTCFLAGS = %%HOSTCFLAGS%% CC = %%CC%% HOSTCC = %%HOSTCC%% BC_LIB_C_ARGS = bc_lib bc_lib_name $(BC_ENABLED_NAME) 1 BC_LIB2_C_ARGS = bc_lib2 bc_lib2_name "$(BC_ENABLED_NAME) && $(BC_ENABLE_EXTRA_MATH_NAME)" 1 OBJS = $(DC_HELP_O) $(BC_HELP_O) $(BC_LIB_O) $(BC_LIB2_O) $(OBJ) all: %%DEFAULT_TARGET%% %%DEFAULT_TARGET%%: %%DEFAULT_TARGET_PREREQS%% %%DEFAULT_TARGET_CMD%% %%SECOND_TARGET%%: %%SECOND_TARGET_PREREQS%% %%SECOND_TARGET_CMD%% $(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_LIB_O): $(BC_LIB_C) $(CC) $(CFLAGS) -o $@ -c $< $(BC_LIB2_C): $(GEN_EXEC) $(BC_LIB2) $(GEN_EMU) $(GEN_EXEC) $(BC_LIB2) $(BC_LIB2_C) $(BC_LIB2_C_ARGS) $(BC_LIB2_O): $(BC_LIB2_C) $(CC) $(CFLAGS) -o $@ -c $< $(BC_HELP_C): $(GEN_EXEC) $(BC_HELP) $(GEN_EMU) $(GEN_EXEC) $(BC_HELP) $(BC_HELP_C) bc_help "" $(BC_ENABLED_NAME) $(BC_HELP_O): $(BC_HELP_C) $(CC) $(CFLAGS) -o $@ -c $< $(DC_HELP_C): $(GEN_EXEC) $(DC_HELP) $(GEN_EMU) $(GEN_EXEC) $(DC_HELP) $(DC_HELP_C) dc_help "" $(DC_ENABLED_NAME) $(DC_HELP_O): $(DC_HELP_C) $(CC) $(CFLAGS) -o $@ -c $< $(BIN): $(MKDIR) -p $(BIN) headers: %%HEADERS%% 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' run_all_tests: %%BC_ALL_TESTS%% %%TIMECONST_ALL_TESTS%% %%DC_ALL_TESTS%% check: test test: %%TESTS%% test_bc: test_bc_header test_bc_tests test_bc_scripts test_bc_stdin test_bc_read test_bc_errors test_bc_other @printf '\nAll bc tests passed.\n\n$(TEST_STARS)\n' test_bc_tests:%%BC_TESTS%% test_bc_scripts:%%BC_SCRIPT_TESTS%% test_bc_stdin: @sh tests/stdin.sh bc %%BC_TEST_EXEC%% test_bc_read: @sh tests/read.sh bc %%BC_TEST_EXEC%% test_bc_errors: @sh tests/errors.sh bc %%BC_TEST_EXEC%% test_bc_other: @sh tests/other.sh bc %%BC_TEST_EXEC%% test_bc_header: @printf '$(TEST_STARS)\n\nRunning bc tests...\n\n' test_dc: test_dc_header test_dc_tests test_dc_scripts test_dc_stdin test_dc_read test_dc_errors test_dc_other @printf '\nAll dc tests passed.\n\n$(TEST_STARS)\n' test_dc_tests:%%DC_TESTS%% test_dc_scripts:%%DC_SCRIPT_TESTS%% test_dc_stdin: @sh tests/stdin.sh dc %%DC_TEST_EXEC%% test_dc_read: @sh tests/read.sh dc %%DC_TEST_EXEC%% test_dc_errors: @sh tests/errors.sh dc %%DC_TEST_EXEC%% test_dc_other: @sh tests/other.sh dc %%DC_TEST_EXEC%% test_dc_header: @printf '$(TEST_STARS)\n\nRunning dc tests...\n\n' timeconst: %%TIMECONST%% library_test: $(LIBBC) $(CC) $(CFLAGS) $(BCL_TEST_C) $(LIBBC) -o $(BCL_TEST) test_library: library_test $(BCL_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 $(MANPAGE) bcl clean_gen: @$(RM) -f $(GEN_EXEC) clean:%%CLEAN_PREREQS%% @printf 'Cleaning files...\n' @$(RM) -f $(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) @$(RM) -fr $(BC_TEST_OUTPUTS) $(DC_TEST_OUTPUTS) @$(RM) -fr $(BC_FUZZ_OUTPUTS) $(DC_FUZZ_OUTPUTS) 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_bcl_manpage: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BCL_MANPAGE) $(DESTDIR)$(MAN3DIR)/$(BCL_MANPAGE_NAME) install_bcl_header: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BCL_HEADER) $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME) install_execs: $(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)" install_library: $(SAFE_INSTALL) $(BINARY_INSTALL_ARGS) $(LIBBC) $(DESTDIR)$(LIBDIR)/$(LIB_NAME) install:%%INSTALL_LOCALES_PREREQS%%%%INSTALL_MAN_PREREQS%%%%INSTALL_PREREQS%% 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_library: $(RM) -f $(DESTDIR)$(LIBDIR)/$(LIB_NAME) uninstall_bcl_header: $(RM) -f $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME) uninstall_bcl_manpage: $(RM) -f $(DESTDIR)$(MAN3DIR)/$(BCL_MANPAGE_NAME) uninstall:%%UNINSTALL_LOCALES_PREREQS%%%%UNINSTALL_MAN_PREREQS%%%%UNINSTALL_PREREQS%% diff --git a/contrib/bc/NEWS.md b/contrib/bc/NEWS.md index 6a8899200f4a..3a3433077d50 100644 --- a/contrib/bc/NEWS.md +++ b/contrib/bc/NEWS.md @@ -1,1030 +1,1056 @@ # News +## 3.3.3 + +This is a production release with one tweak and fixes for manuals. + +The tweak is that `length(0)` returns `1` instead of `0`. In `3.3.1`, I changed +it so `length(0.x)`, where `x` could be any number of digits, returned the +`scale`, but `length(0)` still returned `0` because I believe that `0` has `0` +significant digits. + +After request of FreeBSD and considering the arguments of a mathematician, +compatibility with other `bc`'s, and the expectations of users, I decided to +make the change. + +The fixes for manuals fixed a bug where `--` was rendered as `-`. + +## 3.3.2 + +This is a production release that fixes a divide-by-zero bug in `root()` in the +[extended math library][16]. All previous versions with `root()` have the bug. + +## 3.3.1 + +This is a production release that fixes a bug. + +The bug was in the reporting of number length when the value was 0. + ## 3.3.0 This is a production release that changes one behavior and fixes documentation bugs. The changed behavior is the treatment of `-e` and `-f` when given through `BC_ENV_ARGS` or `DC_ENV_ARGS`. Now `bc` and `dc` do not exit when those options (or their equivalents) are given through those environment variables. However, `bc` and `dc` still exit when they or their equivalents are given on the command-line. ## 3.2.7 This is a production release that removes a small non-portable shell operation in `configure.sh`. This problem was only noticed on OpenBSD, not FreeBSD or Linux. Non-OpenBSD users do ***NOT*** need to upgrade, although NetBSD users may also need to upgrade. ## 3.2.6 This is a production release that fixes the build on FreeBSD. There was a syntax error in `configure.sh` that the Linux shell did not catch, and FreeBSD depends on the existence of `tests/all.sh`. All users that already upgraded to `3.2.5` should update to this release, with my apologies for the poor release of `3.2.5`. Other users should skip `3.2.5` in favor of this version. ## 3.2.5 This is a production release that fixes several bugs and adds a couple small things. The two most important bugs were bugs that causes `dc` to access memory out-of-bounds (crash in debug builds). This was found by upgrading to `afl++` from `afl`. Both were caused by a failure to distinguish between the same two cases. Another bug was the failure to put all of the licenses in the `LICENSE.md` file. Third, some warnings by `scan-build` were found and eliminated. This needed one big change: `bc` and `dc` now bail out as fast as possible on fatal errors instead of unwinding the stack. Fourth, the pseudo-random number now attempts to seed itself with `/dev/random` if `/dev/urandom` fails. Finally, this release has a few quality-of-life changes to the build system. The usage should not change at all; the only thing that changed was making sure the `Makefile.in` was written to rebuild properly when headers changed and to not rebuild when not necessary. ## 3.2.4 This is a production release that fixes a warning on `gcc` 6 or older, which does not have an attribute that is used. Users do ***NOT*** need to upgrade if they don't use `gcc` 6 or older. ## 3.2.3 This is a production release that fixes a bug in `gen/strgen.sh`. I recently changed `gen/strgen.c`, but I did not change `gen/strgen.sh`. Users that do not use `gen/strgen.sh` do not need to upgrade. ## 3.2.2 This is a production release that fixes a portability bug in `configure.sh`. The bug was using the GNU `find` extension `-wholename`. ## 3.2.1 This is a production release that has one fix for `bcl(3)`. It is technically not a bug fix since the behavior is undefined, but the `BclNumber`s that `bcl_divmod()` returns will be set to `BCL_ERROR_INVALID_NUM` if there is an error. Previously, they were not set. ## 3.2.0 This is a production release that has one bug fix and a major addition. The bug fix was a missing `auto` variable in the bessel `j()` function in the math library. The major addition is a way to build a version of `bc`'s math code as a library. This is done with the `-a` option to `configure.sh`. The API for the library can be read in `./manuals/bcl.3.md` or `man bcl` once the library is installed with `make install`. This library was requested by developers before I even finished version 1.0, but I could not figure out how to do it until now. If the library has API breaking changes, the major version of `bc` will be incremented. ## 3.1.6 This is a production release that fixes a new warning from Clang 12 for FreeBSD and also removes some possible undefined behavior found by UBSan that compilers did not seem to take advantage of. Users do ***NOT*** need to upgrade, if they do not want to. ## 3.1.5 This is a production release that fixes the Chinese locales (which caused `bc` to crash) and a crash caused by `bc` executing code when it should not have been able to. ***ALL USERS SHOULD UPGRADE.*** ## 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/ diff --git a/contrib/bc/gen/lib2.bc b/contrib/bc/gen/lib2.bc index b0e651eddcbd..399c7ad3d313 100644 --- a/contrib/bc/gen/lib2.bc +++ b/contrib/bc/gen/lib2.bc @@ -1,317 +1,317 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 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 second bc math library. * */ define p(x,y){ auto a a=y$ if(y==a)return (x^a)@scale return e(y*l(x)) } define r(x,p){ auto t,n if(x==0)return x p=abs(p)$ n=(x<0) x=abs(x) t=x@p if(p=5>>p+1)t+=1>>p if(n)t=-t return t } define ceil(x,p){ auto t,n if(x==0)return x p=abs(p)$ n=(x<0) x=abs(x) t=(x+((x@p>p))@p if(n)t=-t return t } define f(n){ auto r n=abs(n)$ for(r=1;n>1;--n)r*=n return r } define perm(n,k){ auto f,g,s if(k>n)return 0 n=abs(n)$ k=abs(k)$ f=f(n) g=f(n-k) s=scale scale=0 f/=g scale=s return f } define comb(n,r){ auto s,f,g,h if(r>n)return 0 n=abs(n)$ r=abs(r)$ s=scale scale=0 f=f(n) h=f(r) g=f(n-r) f/=h*g scale=s return f } define log(x,b){ auto p,s s=scale if(scalescale)scale=scale(x) scale*=2 p=l(x)/l(b) scale=s return p@s } define l2(x){return log(x,2)} define l10(x){return log(x,A)} define root(x,n){ auto s,m,r,q,p if(n<0)sqrt(n) n=n$ if(n==0)x/n - if(n==1)return x + if(x==0||n==1)return x if(n==2)return sqrt(x) s=scale scale=0 if(x<0&&n%2==0)sqrt(x) scale=s+2 m=(x<0) x=abs(x) p=n-1 q=10^ceil((length(x$)/n)$,0) while(r!=q){ r=q q=(p*r+x/r^p)/n } if(m)r=-r scale=s return r@s } define cbrt(x){return root(x,3)} define pi(s){ auto t,v if(s==0)return 3 s=abs(s)$ t=scale scale=s+1 v=4*a(1) scale=t return v@s } define t(x){ auto s,c,l l=scale scale+=2 s=s(x) c=c(x) scale=l return s/c } define a2(y,x){ auto a,p if(!x&&!y)y/x if(x<=0){ p=pi(scale+2) if(y<0)p=-p } if(x==0)a=p/2 else{ scale+=2 a=a(y/x)+p scale-=2 } return a@scale } define sin(x){return s(x)} define cos(x){return c(x)} define atan(x){return a(x)} define tan(x){return t(x)} define atan2(y,x){return a2(y,x)} define r2d(x){ auto r,i,s s=scale scale+=5 i=ibase ibase=A r=x*180/pi(scale) ibase=i scale=s return r@s } define d2r(x){ auto r,i,s s=scale scale+=5 i=ibase ibase=A r=x*pi(scale)/180 ibase=i scale=s return r@s } define frand(p){ p=abs(p)$ return irand(10^p)>>p } define ifrand(i,p){return irand(abs(i)$)+frand(p)} define srand(x){ if(irand(2))return -x return x } define brand(){return irand(2)} define void output(x,b){ auto c c=obase obase=b x obase=c } define void hex(x){output(x,G)} define void binary(x){output(x,2)} define ubytes(x){ auto p,b,i b=ibase ibase=A x=abs(x)$ i=2^8 for(p=1;i-1p||(!z&&x==p))n*=2 ibase=b return n } define void output_byte(x,i){ auto j,p,y,b j=ibase ibase=A s=scale scale=0 x=abs(x)$ b=x/(2^(i*8)) b%=2^8 y=log(256,obase) if(b>1)p=log(b,obase)+1 else p=b for(i=y-p;i>0;--i)print 0 if(b)print b scale=s ibase=j } define void output_uint(x,n){ auto i,b b=ibase ibase=A for(i=n-1;i>=0;--i){ output_byte(x,i) if(i)print" " else print"\n" } ibase=b } define void hex_uint(x,n){ auto o o=obase obase=G output_uint(x,n) obase=o } define void binary_uint(x,n){ auto o o=obase obase=2 output_uint(x,n) obase=o } define void uintn(x,n){ if(scale(x)){ print"Error: ",x," is not an integer.\n" return } if(x<0){ print"Error: ",x," is negative.\n" return } if(x>=2^(n*8)){ print"Error: ",x," cannot fit into ",n," unsigned byte(s).\n" return } binary_uint(x,n) hex_uint(x,n) } define void intn(x,n){ auto t if(scale(x)){ print"Error: ",x," is not an integer.\n" return } t=2^(n*8-1) if(abs(x)>=t&&(x>0||x!=-t)){ print "Error: ",x," cannot fit into ",n," signed byte(s).\n" return } if(x<0)x=2^(n*8)-(-x) binary_uint(x,n) hex_uint(x,n) } define void uint8(x){uintn(x,1)} define void int8(x){intn(x,1)} define void uint16(x){uintn(x,2)} define void int16(x){intn(x,2)} define void uint32(x){uintn(x,4)} define void int32(x){intn(x,4)} define void uint64(x){uintn(x,8)} define void int64(x){intn(x,8)} define void uint(x){uintn(x,ubytes(x))} define void int(x){intn(x,sbytes(x))} diff --git a/contrib/bc/karatsuba.py b/contrib/bc/karatsuba.py index f8087301f54c..cfab4c4f4fbf 100755 --- a/contrib/bc/karatsuba.py +++ b/contrib/bc/karatsuba.py @@ -1,232 +1,232 @@ #! /usr/bin/python3 -B # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2021 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. # import os import sys import subprocess import time def usage(): print("usage: {} [num_iterations test_num exe]".format(script)) print("\n num_iterations is the number of times to run each karatsuba number; default is 4") print("\n test_num is the last Karatsuba number to run through tests") sys.exit(1) def run(cmd, env=None): return subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) script = sys.argv[0] testdir = os.path.dirname(script) if testdir == "": testdir = os.getcwd() print("\nWARNING: This script is for distro and package maintainers.") print("It is for finding the optimal Karatsuba number.") print("Though it only needs to be run once per release/platform,") print("it takes forever to run.") print("You have been warned.\n") print("Note: If you send an interrupt, it will report the current best number.\n") if __name__ != "__main__": usage() mx = 520 mx2 = mx // 2 mn = 16 num = "9" * mx args_idx = 4 if len(sys.argv) >= 2: num_iterations = int(sys.argv[1]) else: num_iterations = 4 if len(sys.argv) >= 3: test_num = int(sys.argv[2]) else: test_num = 0 if len(sys.argv) >= args_idx: exe = sys.argv[3] else: exe = testdir + "/bin/bc" exedir = os.path.dirname(exe) indata = "for (i = 0; i < 100; ++i) {} * {}\n" indata += "1.23456789^100000\n1.23456789^100000\nhalt" indata = indata.format(num, num).encode() times = [] nums = [] runs = [] nruns = num_iterations + 1 for i in range(0, nruns): runs.append(0) tests = [ "multiply", "modulus", "power", "sqrt" ] scripts = [ "multiply" ] print("Testing CFLAGS=\"-flto\"...") flags = dict(os.environ) try: flags["CFLAGS"] = flags["CFLAGS"] + " " + "-flto" except KeyError: flags["CFLAGS"] = "-flto" p = run([ "./configure.sh", "-O3" ], flags) if p.returncode != 0: print("configure.sh returned an error ({}); exiting...".format(p.returncode)) sys.exit(p.returncode) p = run([ "make" ]) if p.returncode == 0: config_env = flags print("Using CFLAGS=\"-flto\"") else: config_env = os.environ print("Not using CFLAGS=\"-flto\"") p = run([ "make", "clean" ]) -print("Testing \"make -j4\"") +print("Testing \"make -j12\"") if p.returncode != 0: print("make returned an error ({}); exiting...".format(p.returncode)) sys.exit(p.returncode) -p = run([ "make", "-j4" ]) +p = run([ "make", "-j12" ]) if p.returncode == 0: - makecmd = [ "make", "-j4" ] - print("Using \"make -j4\"") + makecmd = [ "make", "-j12" ] + print("Using \"make -j12\"") else: makecmd = [ "make" ] - print("Not using \"make -j4\"") + print("Not using \"make -j12\"") if test_num != 0: mx2 = test_num try: for i in range(mn, mx2 + 1): print("\nCompiling...\n") p = run([ "./configure.sh", "-O3", "-k{}".format(i) ], config_env) if p.returncode != 0: print("configure.sh returned an error ({}); exiting...".format(p.returncode)) sys.exit(p.returncode) p = run(makecmd) if p.returncode != 0: print("make returned an error ({}); exiting...".format(p.returncode)) sys.exit(p.returncode) if (test_num >= i): print("Running tests for Karatsuba Num: {}\n".format(i)) for test in tests: cmd = [ "{}/tests/test.sh".format(testdir), "bc", test, "0", "0", exe ] p = subprocess.run(cmd + sys.argv[args_idx:], stderr=subprocess.PIPE) if p.returncode != 0: print("{} test failed:\n".format(test, p.returncode)) print(p.stderr.decode()) print("\nexiting...") sys.exit(p.returncode) print("") for script in scripts: cmd = [ "{}/tests/script.sh".format(testdir), "bc", script + ".bc", "0", "1", "1", "0", exe ] p = subprocess.run(cmd + sys.argv[args_idx:], stderr=subprocess.PIPE) if p.returncode != 0: print("{} test failed:\n".format(test, p.returncode)) print(p.stderr.decode()) print("\nexiting...") sys.exit(p.returncode) print("") elif test_num == 0: print("Timing Karatsuba Num: {}".format(i), end='', flush=True) for j in range(0, nruns): cmd = [ exe, "{}/tests/bc/power.txt".format(testdir) ] start = time.perf_counter() p = subprocess.run(cmd, input=indata, stdout=subprocess.PIPE, stderr=subprocess.PIPE) end = time.perf_counter() if p.returncode != 0: print("bc returned an error; exiting...") sys.exit(p.returncode) runs[j] = end - start run_times = runs[1:] avg = sum(run_times) / len(run_times) times.append(avg) nums.append(i) print(", Time: {}".format(times[i - mn])) except KeyboardInterrupt: nums = nums[0:i] times = times[0:i] if test_num == 0: opt = nums[times.index(min(times))] print("\n\nOptimal Karatsuba Num (for this machine): {}".format(opt)) print("Run the following:\n") if "-flto" in config_env["CFLAGS"]: print("CFLAGS=\"-flto\" ./configure.sh -O3 -k {}".format(opt)) else: print("./configure.sh -O3 -k {}".format(opt)) print("make") diff --git a/contrib/bc/manuals/bc.1.md.in b/contrib/bc/manuals/bc.1.md.in index 1ce83b8237cd..661fcdd45ae4 100644 --- a/contrib/bc/manuals/bc.1.md.in +++ b/contrib/bc/manuals/bc.1.md.in @@ -1,1822 +1,1821 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. {{ 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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** +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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/A.1 b/contrib/bc/manuals/bc/A.1 index d1e80769c855..b38d8d35e71b 100644 --- a/contrib/bc/manuals/bc/A.1 +++ b/contrib/bc/manuals/bc/A.1 @@ -1,2058 +1,2057 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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 -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/A.1.md b/contrib/bc/manuals/bc/A.1.md index 0cf7a4a0d70e..04f37c6bb724 100644 --- a/contrib/bc/manuals/bc/A.1.md +++ b/contrib/bc/manuals/bc/A.1.md @@ -1,1705 +1,1704 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/E.1 b/contrib/bc/manuals/bc/E.1 index 597cde782788..9023b07c6b87 100644 --- a/contrib/bc/manuals/bc/E.1 +++ b/contrib/bc/manuals/bc/E.1 @@ -1,1314 +1,1313 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/E.1.md b/contrib/bc/manuals/bc/E.1.md index 864cf32068bf..589050cb89b5 100644 --- a/contrib/bc/manuals/bc/E.1.md +++ b/contrib/bc/manuals/bc/E.1.md @@ -1,1094 +1,1093 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/EH.1 b/contrib/bc/manuals/bc/EH.1 index dca77a99162e..53f95b2f7c09 100644 --- a/contrib/bc/manuals/bc/EH.1 +++ b/contrib/bc/manuals/bc/EH.1 @@ -1,1296 +1,1295 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EH.1.md b/contrib/bc/manuals/bc/EH.1.md index c1e324ab6ebc..bfd08efb3830 100644 --- a/contrib/bc/manuals/bc/EH.1.md +++ b/contrib/bc/manuals/bc/EH.1.md @@ -1,1078 +1,1077 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/EHN.1 b/contrib/bc/manuals/bc/EHN.1 index 6b208ade85fd..0870115dca2a 100644 --- a/contrib/bc/manuals/bc/EHN.1 +++ b/contrib/bc/manuals/bc/EHN.1 @@ -1,1289 +1,1288 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EHN.1.md b/contrib/bc/manuals/bc/EHN.1.md index 4ee01a4bbcc8..15b851ee19b0 100644 --- a/contrib/bc/manuals/bc/EHN.1.md +++ b/contrib/bc/manuals/bc/EHN.1.md @@ -1,1070 +1,1069 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/EHNP.1 b/contrib/bc/manuals/bc/EHNP.1 index 7bd46f38e104..f6728d5b2221 100644 --- a/contrib/bc/manuals/bc/EHNP.1 +++ b/contrib/bc/manuals/bc/EHNP.1 @@ -1,1282 +1,1281 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EHNP.1.md b/contrib/bc/manuals/bc/EHNP.1.md index 8aca89e6f7b0..a0e1b71f8d38 100644 --- a/contrib/bc/manuals/bc/EHNP.1.md +++ b/contrib/bc/manuals/bc/EHNP.1.md @@ -1,1064 +1,1063 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/EHP.1 b/contrib/bc/manuals/bc/EHP.1 index 31c02f1b9591..dc3476f68b92 100644 --- a/contrib/bc/manuals/bc/EHP.1 +++ b/contrib/bc/manuals/bc/EHP.1 @@ -1,1289 +1,1288 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .PP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EHP.1.md b/contrib/bc/manuals/bc/EHP.1.md index 2c9ab3909dd6..976ae8eb11b7 100644 --- a/contrib/bc/manuals/bc/EHP.1.md +++ b/contrib/bc/manuals/bc/EHP.1.md @@ -1,1072 +1,1071 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/EN.1 b/contrib/bc/manuals/bc/EN.1 index faa6bf488e28..e6e7b3c5f145 100644 --- a/contrib/bc/manuals/bc/EN.1 +++ b/contrib/bc/manuals/bc/EN.1 @@ -1,1307 +1,1306 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EN.1.md b/contrib/bc/manuals/bc/EN.1.md index c82779aa6818..6dc19727c982 100644 --- a/contrib/bc/manuals/bc/EN.1.md +++ b/contrib/bc/manuals/bc/EN.1.md @@ -1,1086 +1,1085 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/ENP.1 b/contrib/bc/manuals/bc/ENP.1 index 7334888bb012..f96fe194cda1 100644 --- a/contrib/bc/manuals/bc/ENP.1 +++ b/contrib/bc/manuals/bc/ENP.1 @@ -1,1300 +1,1299 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/ENP.1.md b/contrib/bc/manuals/bc/ENP.1.md index 711e3161c162..20b60a7a9081 100644 --- a/contrib/bc/manuals/bc/ENP.1.md +++ b/contrib/bc/manuals/bc/ENP.1.md @@ -1,1080 +1,1079 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/EP.1 b/contrib/bc/manuals/bc/EP.1 index ba27d5cc4862..62ee57bfccc7 100644 --- a/contrib/bc/manuals/bc/EP.1 +++ b/contrib/bc/manuals/bc/EP.1 @@ -1,1307 +1,1306 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] .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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] 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[R] .fi .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Number 6 is a \f[B]non-portable extension\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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 \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below are available when the \f[B]-l\f[R] or -\f[B]\[en]mathlib\f[R] command-line flags are given. +\f[B]--mathlib\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator and the corresponding assignment operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/EP.1.md b/contrib/bc/manuals/bc/EP.1.md index fe6107ce86d7..9a36b99bcb1c 100644 --- a/contrib/bc/manuals/bc/EP.1.md +++ b/contrib/bc/manuals/bc/EP.1.md @@ -1,1088 +1,1087 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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 *scale* of the result is equal to **scale**. 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** +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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/H.1 b/contrib/bc/manuals/bc/H.1 index fb824377e4f1..fe9ac1556522 100644 --- a/contrib/bc/manuals/bc/H.1 +++ b/contrib/bc/manuals/bc/H.1 @@ -1,2038 +1,2037 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/H.1.md b/contrib/bc/manuals/bc/H.1.md index f663b8008c4a..5ba65ba1f5d6 100644 --- a/contrib/bc/manuals/bc/H.1.md +++ b/contrib/bc/manuals/bc/H.1.md @@ -1,1688 +1,1687 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/HN.1 b/contrib/bc/manuals/bc/HN.1 index 0dbb8208f1fa..fe6043eb69d1 100644 --- a/contrib/bc/manuals/bc/HN.1 +++ b/contrib/bc/manuals/bc/HN.1 @@ -1,2031 +1,2030 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/HN.1.md b/contrib/bc/manuals/bc/HN.1.md index cab2e5773219..adf1ffcc29fb 100644 --- a/contrib/bc/manuals/bc/HN.1.md +++ b/contrib/bc/manuals/bc/HN.1.md @@ -1,1680 +1,1679 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/HNP.1 b/contrib/bc/manuals/bc/HNP.1 index 11a8dc2a521f..f407050515b2 100644 --- a/contrib/bc/manuals/bc/HNP.1 +++ b/contrib/bc/manuals/bc/HNP.1 @@ -1,2024 +1,2023 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/HNP.1.md b/contrib/bc/manuals/bc/HNP.1.md index 33feb013e6cf..cd6d2c4836e9 100644 --- a/contrib/bc/manuals/bc/HNP.1.md +++ b/contrib/bc/manuals/bc/HNP.1.md @@ -1,1674 +1,1673 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/HP.1 b/contrib/bc/manuals/bc/HP.1 index 06a46ba5629a..33293307f8f3 100644 --- a/contrib/bc/manuals/bc/HP.1 +++ b/contrib/bc/manuals/bc/HP.1 @@ -1,2031 +1,2030 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .SH OPTIONS .PP The following are the options that bc(1) accepts. .TP -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/HP.1.md b/contrib/bc/manuals/bc/HP.1.md index 7919854a4b5e..7273a346b758 100644 --- a/contrib/bc/manuals/bc/HP.1.md +++ b/contrib/bc/manuals/bc/HP.1.md @@ -1,1682 +1,1681 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/N.1 b/contrib/bc/manuals/bc/N.1 index 0b94f9562d91..faf35eb8b255 100644 --- a/contrib/bc/manuals/bc/N.1 +++ b/contrib/bc/manuals/bc/N.1 @@ -1,2051 +1,2050 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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 -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] section). .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/N.1.md b/contrib/bc/manuals/bc/N.1.md index 0a34edb66f2a..5c877ef79823 100644 --- a/contrib/bc/manuals/bc/N.1.md +++ b/contrib/bc/manuals/bc/N.1.md @@ -1,1697 +1,1696 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-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** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/NP.1 b/contrib/bc/manuals/bc/NP.1 index a89f6ec17271..149037fd9705 100644 --- a/contrib/bc/manuals/bc/NP.1 +++ b/contrib/bc/manuals/bc/NP.1 @@ -1,2044 +1,2043 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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 -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/NP.1.md b/contrib/bc/manuals/bc/NP.1.md index 4aa6923b7494..518d237020df 100644 --- a/contrib/bc/manuals/bc/NP.1.md +++ b/contrib/bc/manuals/bc/NP.1.md @@ -1,1691 +1,1690 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bc/P.1 b/contrib/bc/manuals/bc/P.1 index dc59aa11d961..cfe4afe1fdf3 100644 --- a/contrib/bc/manuals/bc/P.1 +++ b/contrib/bc/manuals/bc/P.1 @@ -1,2051 +1,2050 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH NAME .PP bc - arbitrary-precision decimal arithmetic language and calculator .SH SYNOPSIS .PP -\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]\[en]global-stacks\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]mathlib\f[R]] [\f[B]\[en]no-prompt\f[R]] -[\f[B]\[en]quiet\f[R]] [\f[B]\[en]standard\f[R]] [\f[B]\[en]warn\f[R]] -[\f[B]\[en]version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]bc\f[R] [\f[B]-ghilPqsvVw\f[R]] [\f[B]--global-stacks\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--mathlib\f[R]] +[\f[B]--no-prompt\f[R]] [\f[B]--quiet\f[R]] [\f[B]--standard\f[R]] +[\f[B]--warn\f[R]] [\f[B]--version\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R]. .PP This bc(1) is a drop-in replacement for \f[I]any\f[R] 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 -\f[B]-g\f[R], \f[B]\[en]global-stacks\f[R] +\f[B]-g\f[R], \f[B]--global-stacks\f[R] Turns the globals \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R] 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[R] that simply printed \f[B]x\f[R] in base \f[B]b\f[R] could be written like this: .IP .nf \f[C] define void output(x, b) { obase=b x } \f[R] .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[R] .fi .PP This makes writing functions much easier. .PP (\f[B]Note\f[R]: the function \f[B]output(x,b)\f[R] exists in the extended math library. See the \f[B]LIBRARY\f[R] section.) .PP However, since using this flag means that functions cannot set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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=\[dq]bc -e ibase=A -e obase=8\[dq] alias h2b=\[dq]bc -e ibase=G -e obase=2\[dq] \f[R] .fi .PP Second, if the purpose of a function is to set \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], or \f[B]seed\f[R] 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[R], the value assigned to \f[B]seed\f[R] 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[R] 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[R], it can use the following line: .IP .nf \f[C] seed = seed \f[R] .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[R] and include this option (see the \f[B]ENVIRONMENT VARIABLES\f[R] section for more details). .PP If \f[B]-s\f[R], \f[B]-w\f[R], or any equivalents are used, this option is ignored. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-l\f[R], \f[B]\[en]mathlib\f[R] +\f[B]-l\f[R], \f[B]--mathlib\f[R] Sets \f[B]scale\f[R] (see the \f[B]SYNTAX\f[R] section) to \f[B]20\f[R] 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[R] section. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-q\f[R], \f[B]\[en]quiet\f[R] +\f[B]-q\f[R], \f[B]--quiet\f[R] 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[R], \f[B]-V\f[R], or \f[B]\[en]version\f[R] options are given. +\f[B]-v\f[R], \f[B]-V\f[R], or \f[B]--version\f[R] options are given. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-s\f[R], \f[B]\[en]standard\f[R] +\f[B]-s\f[R], \f[B]--standard\f[R] 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[R]. .RE .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-w\f[R], \f[B]\[en]warn\f[R] -Like \f[B]-s\f[R] and \f[B]\[en]standard\f[R], except that warnings (and +\f[B]-w\f[R], \f[B]--warn\f[R] +Like \f[B]-s\f[R] and \f[B]--standard\f[R], 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[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]BC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]BC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, bc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, bc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]bc >&-\f[R], it will quit with an error. This is done so that bc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other bc(1) implementations, this bc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]bc 2>&-\f[R], it will quit with an error. This is done so that bc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .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[R] means expression, \f[B]S\f[R] means statement, and \f[B]I\f[R] means identifier. .PP Identifiers (\f[B]I\f[R]) start with a lowercase letter and can be followed by any number (up to \f[B]BC_NAME_MAX-1\f[R]) of lowercase letters (\f[B]a-z\f[R]), digits (\f[B]0-9\f[R]), and underscores (\f[B]_\f[R]). The regex is \f[B][a-z][a-z0-9_]*\f[R]. Identifiers with more than one character (letter) are a \f[B]non-portable extension\f[R]. .PP \f[B]ibase\f[R] is a global variable determining how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. -If the \f[B]-s\f[R] (\f[B]\[en]standard\f[R]) and \f[B]-w\f[R] -(\f[B]\[en]warn\f[R]) flags were not given on the command line, the max +If the \f[B]-s\f[R] (\f[B]--standard\f[R]) and \f[B]-w\f[R] +(\f[B]--warn\f[R]) flags were not given on the command line, the max allowable value for \f[B]ibase\f[R] is \f[B]36\f[R]. Otherwise, it is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in bc(1) programs with the \f[B]maxibase()\f[R] built-in function. .PP \f[B]obase\f[R] is a global variable determining how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]BC_BASE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxobase()\f[R] built-in function. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a global variable that sets the precision of any operations, with exceptions. \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] is \f[B]BC_SCALE_MAX\f[R] and can be queried in bc(1) programs with the \f[B]maxscale()\f[R] built-in function. .PP bc(1) has both \f[I]global\f[R] variables and \f[I]local\f[R] variables. All \f[I]local\f[R] variables are local to the function; they are parameters or are introduced in the \f[B]auto\f[R] list of a function (see the \f[B]FUNCTIONS\f[R] section). If a variable is accessed which is not a parameter or in the \f[B]auto\f[R] list, it is assumed to be \f[I]global\f[R]. If a parent function has a \f[I]local\f[R] variable version of a variable that a child function considers \f[I]global\f[R], the value of that \f[I]global\f[R] 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[R] 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[R] the expression is notsurrounded by parentheses. .PP The value that is printed is also assigned to the special variable \f[B]last\f[R]. A single dot (\f[B].\f[R]) may also be used as a synonym for \f[B]last\f[R]. These are \f[B]non-portable extensions\f[R]. .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[R] and \f[B]*/\f[R]. .IP "2." 3 Line comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SS Named Expressions .PP The following are named expressions in bc(1): .IP "1." 3 Variables: \f[B]I\f[R] .IP "2." 3 Array Elements: \f[B]I[E]\f[R] .IP "3." 3 \f[B]ibase\f[R] .IP "4." 3 \f[B]obase\f[R] .IP "5." 3 \f[B]scale\f[R] .IP "6." 3 \f[B]seed\f[R] .IP "7." 3 \f[B]last\f[R] or a single dot (\f[B].\f[R]) .PP Numbers 6 and 7 are \f[B]non-portable extensions\f[R]. .PP The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] value is assigned to \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if \f[B]seed\f[R] is queried again immediately. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] will \f[I]not\f[R] produce unique sequences of pseudo-random numbers. The value of \f[B]seed\f[R] will change after any use of the \f[B]rand()\f[R] and \f[B]irand(E)\f[R] operands (see the \f[I]Operands\f[R] subsection below), except if the parameter passed to \f[B]irand(E)\f[R] is \f[B]0\f[R], \f[B]1\f[R], or negative. .PP There is no limit to the length (number of significant decimal digits) or \f[I]scale\f[R] of the value that can be assigned to \f[B]seed\f[R]. .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[R] 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[R]/\f[B]decrement\f[R] operators and as the left side of \f[B]assignment\f[R] operators (see the \f[I]Operators\f[R] subsection). .SS Operands .PP The following are valid operands in bc(1): .IP " 1." 4 Numbers (see the \f[I]Numbers\f[R] subsection below). .IP " 2." 4 Array indices (\f[B]I[E]\f[R]). .IP " 3." 4 \f[B](E)\f[R]: The value of \f[B]E\f[R] (used to change precedence). .IP " 4." 4 \f[B]sqrt(E)\f[R]: The square root of \f[B]E\f[R]. \f[B]E\f[R] must be non-negative. .IP " 5." 4 \f[B]length(E)\f[R]: The number of significant decimal digits in \f[B]E\f[R]. .IP " 6." 4 \f[B]length(I[])\f[R]: The number of elements in the array \f[B]I\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 7." 4 \f[B]scale(E)\f[R]: The \f[I]scale\f[R] of \f[B]E\f[R]. .IP " 8." 4 \f[B]abs(E)\f[R]: The absolute value of \f[B]E\f[R]. This is a \f[B]non-portable extension\f[R]. .IP " 9." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a non-\f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] section) if the corresponding parameter in the function definition is an array reference. .IP "10." 4 \f[B]read()\f[R]: Reads a line from \f[B]stdin\f[R] and uses that as an expression. The result of that expression is the result of the \f[B]read()\f[R] operand. This is a \f[B]non-portable extension\f[R]. .IP "11." 4 \f[B]maxibase()\f[R]: The max allowable \f[B]ibase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "12." 4 \f[B]maxobase()\f[R]: The max allowable \f[B]obase\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "13." 4 \f[B]maxscale()\f[R]: The max allowable \f[B]scale\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "14." 4 \f[B]rand()\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and \f[B]BC_RAND_MAX\f[R] (inclusive). Using this operand will change the value of \f[B]seed\f[R]. This is a \f[B]non-portable extension\f[R]. .IP "15." 4 \f[B]irand(E)\f[R]: A pseudo-random integer between \f[B]0\f[R] (inclusive) and the value of \f[B]E\f[R] (exclusive). If \f[B]E\f[R] is negative or is a non-integer (\f[B]E\f[R]\[cq]s \f[I]scale\f[R] is not \f[B]0\f[R]), an error is raised, and bc(1) resets (see the \f[B]RESET\f[R] section) while \f[B]seed\f[R] remains unchanged. If \f[B]E\f[R] is larger than \f[B]BC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]BC_RAND_MAX+1\f[R], 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[R], unless the value of \f[B]E\f[R] is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. This is a \f[B]non-portable extension\f[R]. .IP "16." 4 \f[B]maxrand()\f[R]: The max integer returned by \f[B]rand()\f[R]. This is a \f[B]non-portable extension\f[R]. .PP The integers generated by \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to be as unbiased as possible, subject to the limitations of the pseudo-random number generator. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with \f[B]rand()\f[R] and \f[B]irand(E)\f[R] are guaranteed to \f[I]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .SS Numbers .PP Numbers are strings made up of digits, uppercase letters, and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]BC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]Z\f[R] alone always equals decimal \f[B]35\f[R]. .PP In addition, bc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e-3\f[R] is equal to \f[B]0.0042890\f[R]. .PP Using scientific notation is an error or warning if the \f[B]-s\f[R] or \f[B]-w\f[R], respectively, command-line options (or equivalents) are given. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bc(1) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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 -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] Type: Prefix and Postfix .RS .PP Associativity: None .PP Description: \f[B]increment\f[R], \f[B]decrement\f[R] .RE .TP \f[B]-\f[R] \f[B]!\f[R] Type: Prefix .RS .PP Associativity: None .PP Description: \f[B]negation\f[R], \f[B]boolean not\f[R] .RE .TP \f[B]$\f[R] Type: Postfix .RS .PP Associativity: None .PP Description: \f[B]truncation\f[R] .RE .TP \f[B]\[at]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]set precision\f[R] .RE .TP \f[B]\[ha]\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]power\f[R] .RE .TP \f[B]*\f[R] \f[B]/\f[R] \f[B]%\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]multiply\f[R], \f[B]divide\f[R], \f[B]modulus\f[R] .RE .TP \f[B]+\f[R] \f[B]-\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]add\f[R], \f[B]subtract\f[R] .RE .TP \f[B]<<\f[R] \f[B]>>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]shift left\f[R], \f[B]shift right\f[R] .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] Type: Binary .RS .PP Associativity: Right .PP Description: \f[B]assignment\f[R] .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]relational\f[R] .RE .TP \f[B]&&\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean and\f[R] .RE .TP \f[B]||\f[R] Type: Binary .RS .PP Associativity: Left .PP Description: \f[B]boolean or\f[R] .RE .PP The operators will be described in more detail below. .TP -\f[B]++\f[R] \f[B]\[en]\f[R] +\f[B]++\f[R] \f[B]--\f[R] The prefix and postfix \f[B]increment\f[R] and \f[B]decrement\f[R] operators behave exactly like they would in C. They require a named expression (see the \f[I]Named Expressions\f[R] subsection) as an operand. .RS .PP The prefix versions of these operators are more efficient; use them where possible. .RE .TP \f[B]-\f[R] The \f[B]negation\f[R] operator returns \f[B]0\f[R] if a user attempts to negate any expression with the value \f[B]0\f[R]. Otherwise, a copy of the expression with its sign flipped is returned. .TP \f[B]!\f[R] The \f[B]boolean not\f[R] operator returns \f[B]1\f[R] if the expression is \f[B]0\f[R], or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]$\f[R] The \f[B]truncation\f[R] operator returns a copy of the given expression with all of its \f[I]scale\f[R] removed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[at]\f[R] The \f[B]set precision\f[R] operator takes two expressions and returns a copy of the first with its \f[I]scale\f[R] 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[R] 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[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]\[ha]\f[R] The \f[B]power\f[R] operator (not the \f[B]exclusive or\f[R] operator, as it would be in C) takes two expressions and raises the first to the power of the value of the second. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]), and if it is negative, the first value must be non-zero. .RE .TP \f[B]*\f[R] The \f[B]multiply\f[R] operator takes two expressions, multiplies them, and returns the product. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The \f[B]divide\f[R] operator takes two expressions, divides them, and returns the quotient. The \f[I]scale\f[R] of the result shall be the value of \f[B]scale\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]%\f[R] The \f[B]modulus\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and evaluates them by 1) Computing \f[B]a/b\f[R] to current \f[B]scale\f[R] and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .RS .PP The second expression must be non-zero. .RE .TP \f[B]+\f[R] The \f[B]add\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the sum, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]-\f[R] The \f[B]subtract\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns the difference, with a \f[I]scale\f[R] equal to the max of the \f[I]scale\f[R]s of \f[B]a\f[R] and \f[B]b\f[R]. .TP \f[B]<<\f[R] The \f[B]left shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the right. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]>>\f[R] The \f[B]right shift\f[R] operator takes two expressions, \f[B]a\f[R] and \f[B]b\f[R], and returns a copy of the value of \f[B]a\f[R] with its decimal point moved \f[B]b\f[R] places to the left. .RS .PP The second expression must be an integer (no \f[I]scale\f[R]) and non-negative. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R] \f[B]<<=\f[R] \f[B]>>=\f[R] \f[B]+=\f[R] \f[B]-=\f[R] \f[B]*=\f[R] \f[B]/=\f[R] \f[B]%=\f[R] \f[B]\[ha]=\f[R] \f[B]\[at]=\f[R] The \f[B]assignment\f[R] operators take two expressions, \f[B]a\f[R] and \f[B]b\f[R] where \f[B]a\f[R] is a named expression (see the \f[I]Named Expressions\f[R] subsection). .RS .PP For \f[B]=\f[R], \f[B]b\f[R] is copied and the result is assigned to \f[B]a\f[R]. For all others, \f[B]a\f[R] and \f[B]b\f[R] are applied as operands to the corresponding arithmetic operator and the result is assigned to \f[B]a\f[R]. .PP The \f[B]assignment\f[R] operators that correspond to operators that are extensions are themselves \f[B]non-portable extensions\f[R]. .RE .TP \f[B]==\f[R] \f[B]<=\f[R] \f[B]>=\f[R] \f[B]!=\f[R] \f[B]<\f[R] \f[B]>\f[R] The \f[B]relational\f[R] operators compare two expressions, \f[B]a\f[R] and \f[B]b\f[R], and if the relation holds, according to C language semantics, the result is \f[B]1\f[R]. Otherwise, it is \f[B]0\f[R]. .RS .PP Note that unlike in C, these operators have a lower precedence than the \f[B]assignment\f[R] operators, which means that \f[B]a=b>c\f[R] is interpreted as \f[B](a=b)>c\f[R]. .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[R]. .RE .TP \f[B]&&\f[R] The \f[B]boolean and\f[R] operator takes two expressions and returns \f[B]1\f[R] if both expressions are non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]||\f[R] The \f[B]boolean or\f[R] operator takes two expressions and returns \f[B]1\f[R] if one of the expressions is non-zero, \f[B]0\f[R] otherwise. .RS .PP This is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Statements .PP The following items are statements: .IP " 1." 4 \f[B]E\f[R] .IP " 2." 4 \f[B]{\f[R] \f[B]S\f[R] \f[B];\f[R] \&... \f[B];\f[R] \f[B]S\f[R] \f[B]}\f[R] .IP " 3." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 4." 4 \f[B]if\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] \f[B]else\f[R] \f[B]S\f[R] .IP " 5." 4 \f[B]while\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 6." 4 \f[B]for\f[R] \f[B](\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B];\f[R] \f[B]E\f[R] \f[B])\f[R] \f[B]S\f[R] .IP " 7." 4 An empty statement .IP " 8." 4 \f[B]break\f[R] .IP " 9." 4 \f[B]continue\f[R] .IP "10." 4 \f[B]quit\f[R] .IP "11." 4 \f[B]halt\f[R] .IP "12." 4 \f[B]limits\f[R] .IP "13." 4 A string of characters, enclosed in double quotes .IP "14." 4 \f[B]print\f[R] \f[B]E\f[R] \f[B],\f[R] \&... \f[B],\f[R] \f[B]E\f[R] .IP "15." 4 \f[B]I()\f[R], \f[B]I(E)\f[R], \f[B]I(E, E)\f[R], and so on, where \f[B]I\f[R] is an identifier for a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). The \f[B]E\f[R] argument(s) may also be arrays of the form \f[B]I[]\f[R], which will automatically be turned into array references (see the \f[I]Array References\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]. .PP Also, as a \f[B]non-portable extension\f[R], 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[R]. .PP The \f[B]break\f[R] 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[R] 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[R] \f[B]else\f[R] statement does the same thing as in C. .PP The \f[B]quit\f[R] 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[R] statement causes bc(1) to quit, if it is executed. (Unlike \f[B]quit\f[R] if it is on a branch of an \f[B]if\f[R] statement that is not executed, bc(1) does not quit.) .PP The \f[B]limits\f[R] statement prints the limits that this bc(1) is subject to. This is like the \f[B]quit\f[R] 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[R] to \f[B]obase\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Scientific notation and engineering notation are disabled if bc(1) is run with either the \f[B]-s\f[R] or \f[B]-w\f[R] command-line options (or equivalents). .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .SS Print Statement .PP The \[lq]expressions\[rq] in a \f[B]print\f[R] 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]\[rs]a\f[R] T}@T{ \f[B]\[rs]a\f[R] T} T{ \f[B]\[rs]b\f[R] T}@T{ \f[B]\[rs]b\f[R] T} T{ \f[B]\[rs]\[rs]\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]e\f[R] T}@T{ \f[B]\[rs]\f[R] T} T{ \f[B]\[rs]f\f[R] T}@T{ \f[B]\[rs]f\f[R] T} T{ \f[B]\[rs]n\f[R] T}@T{ \f[B]\[rs]n\f[R] T} T{ \f[B]\[rs]q\f[R] T}@T{ \f[B]\[dq]\f[R] T} T{ \f[B]\[rs]r\f[R] T}@T{ \f[B]\[rs]r\f[R] T} T{ \f[B]\[rs]t\f[R] T}@T{ \f[B]\[rs]t\f[R] 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[R], 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[R] is equal to \f[B]0\f[R], in the expression .IP .nf \f[C] a[i++] = i++ \f[R] .fi .PP the first (or 0th) element of \f[B]a\f[R] is set to \f[B]1\f[R], and \f[B]i\f[R] is equal to \f[B]2\f[R] at the end of the expression. .PP This includes function arguments. Thus, assuming \f[B]i\f[R] is equal to \f[B]0\f[R], this means that in the expression .IP .nf \f[C] x(i++, i++) \f[R] .fi .PP the first argument passed to \f[B]x()\f[R] is \f[B]0\f[R], and the second argument is \f[B]1\f[R], while \f[B]i\f[R] is equal to \f[B]2\f[R] 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[R] .fi .PP Any \f[B]I\f[R] in the parameter list or \f[B]auto\f[R] list may be replaced with \f[B]I[]\f[R] to make a parameter or \f[B]auto\f[R] var an array, and any \f[B]I\f[R] in the parameter list may be replaced with \f[B]*I[]\f[R] 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[R] like normal array parameters and will be automatically converted into references. .PP As a \f[B]non-portable extension\f[R], the opening brace of a \f[B]define\f[R] statement may appear on the next line. .PP As a \f[B]non-portable extension\f[R], the return statement may also be in one of the following forms: .IP "1." 3 \f[B]return\f[R] .IP "2." 3 \f[B]return\f[R] \f[B](\f[R] \f[B])\f[R] .IP "3." 3 \f[B]return\f[R] \f[B]E\f[R] .PP The first two, or not specifying a \f[B]return\f[R] statement, is equivalent to \f[B]return (0)\f[R], unless the function is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection below). .SS Void Functions .PP Functions can also be \f[B]void\f[R] functions, defined as follows: .IP .nf \f[C] define void I(I,...,I){ auto I,...,I S;...;S return } \f[R] .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[R] statements listed above. They can also omit the return statement entirely. .PP The word \[lq]void\[rq] is not treated as a keyword; it is still possible to have variables, arrays, and functions named \f[B]void\f[R]. The word \[lq]void\[rq] is only treated specially right after the \f[B]define\f[R] keyword. .PP This is a \f[B]non-portable extension\f[R]. .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[R] .fi .PP it is a \f[B]reference\f[R]. 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[R]. .SH LIBRARY .PP All of the functions below, including the functions in the extended math library (see the \f[I]Extended Library\f[R] subsection below), are -available when the \f[B]-l\f[R] or \f[B]\[en]mathlib\f[R] command-line +available when the \f[B]-l\f[R] or \f[B]--mathlib\f[R] command-line flags are given, except that the extended math library is not available when the \f[B]-s\f[R] option, the \f[B]-w\f[R] 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 \f[B]s(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]c(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l(x)\f[R] Returns the natural logarithm of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]e(x)\f[R] Returns the mathematical constant \f[B]e\f[R] raised to the power of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]j(x, n)\f[R] Returns the bessel integer order \f[B]n\f[R] (truncated) of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .SS Extended Library .PP The extended library is \f[I]not\f[R] loaded when the -\f[B]-s\f[R]/\f[B]\[en]standard\f[R] or \f[B]-w\f[R]/\f[B]\[en]warn\f[R] +\f[B]-s\f[R]/\f[B]--standard\f[R] or \f[B]-w\f[R]/\f[B]--warn\f[R] 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[R]. .TP \f[B]p(x, y)\f[R] Calculates \f[B]x\f[R] to the power of \f[B]y\f[R], even if \f[B]y\f[R] is not an integer, and returns the result to the current \f[B]scale\f[R]. .RS .PP It is an error if \f[B]y\f[R] is negative and \f[B]x\f[R] is \f[B]0\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round half away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero). .TP \f[B]ceil(x, p)\f[R] Returns \f[B]x\f[R] rounded to \f[B]p\f[R] decimal places according to the rounding mode round away from \f[B]0\f[R] (https://en.wikipedia.org/wiki/Rounding#Rounding_away_from_zero). .TP \f[B]f(x)\f[R] Returns the factorial of the truncated absolute value of \f[B]x\f[R]. .TP \f[B]perm(n, k)\f[R] Returns the permutation of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]comb(n, k)\f[R] Returns the combination of the truncated absolute value of \f[B]n\f[R] of the truncated absolute value of \f[B]k\f[R], if \f[B]k <= n\f[R]. If not, it returns \f[B]0\f[R]. .TP \f[B]l2(x)\f[R] Returns the logarithm base \f[B]2\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]l10(x)\f[R] Returns the logarithm base \f[B]10\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]log(x, b)\f[R] Returns the logarithm base \f[B]b\f[R] of \f[B]x\f[R]. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cbrt(x)\f[R] Returns the cube root of \f[B]x\f[R]. .TP \f[B]root(x, n)\f[R] Calculates the truncated value of \f[B]n\f[R], \f[B]r\f[R], and returns the \f[B]r\f[R]th root of \f[B]x\f[R] to the current \f[B]scale\f[R]. .RS .PP If \f[B]r\f[R] is \f[B]0\f[R] or negative, this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). It also raises an error and causes bc(1) to reset if \f[B]r\f[R] is even and \f[B]x\f[R] is negative. .RE .TP \f[B]pi(p)\f[R] Returns \f[B]pi\f[R] to \f[B]p\f[R] decimal places. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]t(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]a2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]sin(x)\f[R] Returns the sine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]s(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]cos(x)\f[R] Returns the cosine of \f[B]x\f[R], which is assumed to be in radians. .RS .PP This is an alias of \f[B]c(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]tan(x)\f[R] Returns the tangent of \f[B]x\f[R], which is assumed to be in radians. .RS .PP If \f[B]x\f[R] is equal to \f[B]1\f[R] or \f[B]-1\f[R], this raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). .PP This is an alias of \f[B]t(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan(x)\f[R] Returns the arctangent of \f[B]x\f[R], in radians. .RS .PP This is an alias of \f[B]a(x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]atan2(y, x)\f[R] Returns the arctangent of \f[B]y/x\f[R], in radians. If both \f[B]y\f[R] and \f[B]x\f[R] are equal to \f[B]0\f[R], it raises an error and causes bc(1) to reset (see the \f[B]RESET\f[R] section). Otherwise, if \f[B]x\f[R] is greater than \f[B]0\f[R], it returns \f[B]a(y/x)\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is greater than or equal to \f[B]0\f[R], it returns \f[B]a(y/x)+pi\f[R]. If \f[B]x\f[R] is less than \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]a(y/x)-pi\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is greater than \f[B]0\f[R], it returns \f[B]pi/2\f[R]. If \f[B]x\f[R] is equal to \f[B]0\f[R], and \f[B]y\f[R] is less than \f[B]0\f[R], it returns \f[B]-pi/2\f[R]. .RS .PP This function is the same as the \f[B]atan2()\f[R] function in many programming languages. .PP This is an alias of \f[B]a2(y, x)\f[R]. .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]r2d(x)\f[R] Converts \f[B]x\f[R] from radians to degrees and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]d2r(x)\f[R] Converts \f[B]x\f[R] from degrees to radians and returns the result. .RS .PP This is a transcendental function (see the \f[I]Transcendental Functions\f[R] subsection below). .RE .TP \f[B]frand(p)\f[R] Generates a pseudo-random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]. If \f[B]p\f[R] is \f[B]0\f[R], then \f[B]0\f[R] is returned, and \f[B]seed\f[R] is \f[I]not\f[R] changed. .TP \f[B]ifrand(i, p)\f[R] Generates a pseudo-random number that is between \f[B]0\f[R] (inclusive) and the truncated absolute value of \f[B]i\f[R] (exclusive) with the number of decimal digits after the decimal point equal to the truncated absolute value of \f[B]p\f[R]. If the absolute value of \f[B]i\f[R] is greater than or equal to \f[B]2\f[R], and \f[B]p\f[R] is not \f[B]0\f[R], then calling this function will change the value of \f[B]seed\f[R]; otherwise, \f[B]0\f[R] is returned and \f[B]seed\f[R] is not changed. .TP \f[B]srand(x)\f[R] Returns \f[B]x\f[R] with its sign flipped with probability \f[B]0.5\f[R]. In other words, it randomizes the sign of \f[B]x\f[R]. .TP \f[B]brand()\f[R] Returns a random boolean value (either \f[B]0\f[R] or \f[B]1\f[R]). .TP \f[B]ubytes(x)\f[R] Returns the numbers of unsigned integer bytes required to hold the truncated absolute value of \f[B]x\f[R]. .TP \f[B]sbytes(x)\f[R] Returns the numbers of signed, two\[cq]s-complement integer bytes required to hold the truncated value of \f[B]x\f[R]. .TP \f[B]hex(x)\f[R] Outputs the hexadecimal (base \f[B]16\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary(x)\f[R] Outputs the binary (base \f[B]2\f[R]) representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output(x, b)\f[R] Outputs the base \f[B]b\f[R] representation of \f[B]x\f[R]. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] 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[R] 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[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]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[R] is not an integer, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uintn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]intn(x, n)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]n\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]n\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int8(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]1\f[R] byte. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]1\f[R] byte, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int16(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]2\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]2\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int32(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]4\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]4\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]uint64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as an unsigned integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer, is negative, or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]int64(x)\f[R] Outputs the representation, in binary and hexadecimal, of \f[B]x\f[R] as a signed, two\[cq]s-complement integer in \f[B]8\f[R] bytes. Both outputs are split into bytes separated by spaces. .RS .PP If \f[B]x\f[R] is not an integer or cannot fit into \f[B]8\f[R] bytes, an error message is printed instead, but bc(1) is not reset (see the \f[B]RESET\f[R] section). .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]hex_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in hexadecimal using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]binary_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in binary using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_uint(x, n)\f[R] Outputs the representation of the truncated absolute value of \f[B]x\f[R] as an unsigned integer in the current \f[B]obase\f[R] (see the \f[B]SYNTAX\f[R] section) using \f[B]n\f[R] bytes. Not all of the value will be output if \f[B]n\f[R] is too small. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] section). .RE .TP \f[B]output_byte(x, i)\f[R] Outputs byte \f[B]i\f[R] of the truncated absolute value of \f[B]x\f[R], where \f[B]0\f[R] is the least significant byte and \f[B]number_of_bytes - 1\f[R] is the most significant byte. .RS .PP This is a \f[B]void\f[R] function (see the \f[I]Void Functions\f[R] subsection of the \f[B]FUNCTIONS\f[R] 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[R]) set to at least 1 higher than is necessary. If exact results are \f[I]absolutely\f[R] required, users can double the precision (\f[B]scale\f[R]) and then truncate. .PP The transcendental functions in the standard math library are: .IP \[bu] 2 \f[B]s(x)\f[R] .IP \[bu] 2 \f[B]c(x)\f[R] .IP \[bu] 2 \f[B]a(x)\f[R] .IP \[bu] 2 \f[B]l(x)\f[R] .IP \[bu] 2 \f[B]e(x)\f[R] .IP \[bu] 2 \f[B]j(x, n)\f[R] .PP The transcendental functions in the extended math library are: .IP \[bu] 2 \f[B]l2(x)\f[R] .IP \[bu] 2 \f[B]l10(x)\f[R] .IP \[bu] 2 \f[B]log(x, b)\f[R] .IP \[bu] 2 \f[B]pi(p)\f[R] .IP \[bu] 2 \f[B]t(x)\f[R] .IP \[bu] 2 \f[B]a2(y, x)\f[R] .IP \[bu] 2 \f[B]sin(x)\f[R] .IP \[bu] 2 \f[B]cos(x)\f[R] .IP \[bu] 2 \f[B]tan(x)\f[R] .IP \[bu] 2 \f[B]atan(x)\f[R] .IP \[bu] 2 \f[B]atan2(y, x)\f[R] .IP \[bu] 2 \f[B]r2d(x)\f[R] .IP \[bu] 2 \f[B]d2r(x)\f[R] .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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP The actual values of \f[B]BC_LONG_BIT\f[R] and \f[B]BC_BASE_DIGS\f[R] can be queried with the \f[B]limits\f[R] 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[R], 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 \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]rand()\f[R] operand. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .PP The actual values can be queried with the \f[B]limits\f[R] 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 \f[B]POSIXLY_CORRECT\f[R] If this variable exists (no matter the contents), bc(1) behaves as if the \f[B]-s\f[R] option was given. .TP \f[B]BC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some bc file.bc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]bc\[dq] file.bc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `bc' file.bc\[dq]\f[R], 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[R] 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 \f[B]BC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), bc(1) will output lines to that length, including the backslash (\f[B]\[rs]\f[R]). The default line length is \f[B]70\f[R]. .SH EXIT STATUS .PP bc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]<<\f[R]), and right shift (\f[B]>>\f[R]) operators and their corresponding assignment operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], 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[R] subsection of the \f[B]SYNTAX\f[R] section), giving an invalid \f[B]auto\f[R] list, having a duplicate \f[B]auto\f[R]/function parameter, failing to find the end of a code block, attempting to return a value from a \f[B]void\f[R] function, attempting to use a variable as a reference, and using any extensions when the option \f[B]-s\f[R] or any equivalents were given. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] 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[R] function call as a value in an expression. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, bc(1) always exits and returns \f[B]4\f[R], 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[R] section), since bc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, bc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If bc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when bc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .SH SEE ALSO .PP dc(1) .SH STANDARDS .PP bc(1) is compliant with the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification. The flags \f[B]-efghiqsvVw\f[R], 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[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. .PP This bc(1) supports error messages for different locales, and thus, it supports \f[B]LC_MESSAGES\f[R]. .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bc/P.1.md b/contrib/bc/manuals/bc/P.1.md index 7e6dcee4747d..489af865475c 100644 --- a/contrib/bc/manuals/bc/P.1.md +++ b/contrib/bc/manuals/bc/P.1.md @@ -1,1699 +1,1698 @@ # NAME bc - arbitrary-precision decimal 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*...] +**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** +**-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** +**-h**, **-\-help** : Prints a usage message and quits. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-l**, **--mathlib** +**-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** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-q**, **--quiet** +**-q**, **-\-quiet** : 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. + **-\-version** options are given. This is a **non-portable extension**. -**-s**, **--standard** +**-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** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. This is a **non-portable extension**. -**-w**, **--warn** +**-w**, **-\-warn** -: Like **-s** and **--standard**, except that warnings (and not errors) are +: 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* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, bc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **BC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, bc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, bc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **BC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then 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 + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, 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**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 +**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. This means that the pseudo-random values from bc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. ## 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e-3** is equal to **0.0042890**. 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 *scale* of the result is equal to **scale**. 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 +**-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 +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**. It is an error if **y** is negative and **x** is **0**. 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**. # 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/bcl.3 b/contrib/bc/manuals/bcl.3 index 99040581a153..d83a2d3ad2e5 100644 --- a/contrib/bc/manuals/bcl.3 +++ b/contrib/bc/manuals/bcl.3 @@ -1,1365 +1,1365 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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 "BCL" "3" "February 2021" "Gavin D. Howard" "Libraries Manual" +.TH "BCL" "3" "March 2021" "Gavin D. Howard" "Libraries Manual" .SH NAME .PP bcl - library of arbitrary precision decimal arithmetic .SH SYNOPSIS .SS Use .PP \f[I]#include \f[R] .PP Link with \f[I]-lbcl\f[R]. .SS Signals .PP This procedure will allow clients to use signals to interrupt computations running in bcl(3). .PP \f[B]void bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]bool bcl_running(\f[R]\f[I]void\f[R]\f[B]);\f[R] .SS Setup .PP These items allow clients to set up bcl(3). .PP \f[B]BclError bcl_init(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_free(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]bool bcl_abortOnFatalError(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_setAbortOnFatalError(bool\f[R] \f[I]abrt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_gc(\f[R]\f[I]void\f[R]\f[B]);\f[R] .SS Contexts .PP These items will allow clients to handle contexts, which are isolated from each other. This allows more than one client to use bcl(3) in the same program. .PP \f[B]struct BclCtxt;\f[R] .PP \f[B]typedef struct BclCtxt* BclContext;\f[R] .PP \f[B]BclContext bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_free(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_pushContext(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_popContext(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclContext bcl_context(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_freeNums(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_ctxt_scale(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_setScale(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_ctxt_ibase(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_setIbase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]ibase\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_ctxt_obase(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_setObase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]obase\f[R]\f[B]);\f[R] .SS Errors .PP These items allow clients to handle errors. .PP \f[B]typedef enum BclError BclError;\f[R] .PP \f[B]BclError bcl_err(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .SS Numbers .PP These items allow clients to manipulate and query the arbitrary-precision numbers managed by bcl(3). .PP \f[B]typedef struct { size_t i; } BclNumber;\f[R] .PP \f[B]BclNumber bcl_num_create(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_num_free(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]bool bcl_num_neg(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]void bcl_num_setNeg(BclNumber\f[R] \f[I]n\f[R]\f[B], bool\f[R] \f[I]neg\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_num_scale(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_num_setScale(BclNumber\f[R] \f[I]n\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_num_len(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .SS Conversion .PP These items allow clients to convert numbers into and from strings and integers. .PP \f[B]BclNumber bcl_parse(const char *restrict\f[R] \f[I]val\f[R]\f[B]);\f[R] .PP \f[B]char* bcl_string(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_bigdig(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig *\f[R]\f[I]result\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_bigdig2num(BclBigDig\f[R] \f[I]val\f[R]\f[B]);\f[R] .SS Math .PP These items allow clients to run math on numbers. .PP \f[B]BclNumber bcl_add(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_sub(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_mul(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_div(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_mod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_pow(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_lshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_rshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_sqrt(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_divmod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], BclNumber *\f[R]\f[I]d\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_modexp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B]);\f[R] .SS Miscellaneous .PP These items are miscellaneous. .PP \f[B]void bcl_zero(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]void bcl_one(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]ssize_t bcl_cmp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_copy(BclNumber\f[R] \f[I]d\f[R]\f[B], BclNumber\f[R] \f[I]s\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_dup(BclNumber\f[R] \f[I]s\f[R]\f[B]);\f[R] .SS Pseudo-Random Number Generator .PP These items allow clients to manipulate the seeded pseudo-random number generator in bcl(3). .PP \f[B]#define BCL_SEED_ULONGS\f[R] .PP \f[B]#define BCL_SEED_SIZE\f[R] .PP \f[B]typedef unsigned long BclBigDig;\f[R] .PP \f[B]typedef unsigned long BclRandInt;\f[R] .PP \f[B]BclNumber bcl_irand(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_frand(size_t\f[R] \f[I]places\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_ifrand(BclNumber\f[R] \f[I]a\f[R]\f[B], size_t\f[R] \f[I]places\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_rand_seedWithNum(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_rand_seed(unsigned char\f[R] \f[I]seed\f[R]\f[B][\f[R]\f[I]BC_SEED_SIZE\f[R]\f[B]]);\f[R] .PP \f[B]void bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclRandInt bcl_rand_int(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclRandInt bcl_rand_bounded(BclRandInt\f[R] \f[I]bound\f[R]\f[B]);\f[R] .SH DESCRIPTION .PP bcl(3) is a library that implements arbitrary-precision decimal math, as standardized by POSIX (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) in bc(1). .PP bcl(3) is async-signal-safe if \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] is used properly. (See the \f[B]SIGNAL HANDLING\f[R] section.) .PP All of the items in its interface are described below. See the documentation for each function for what each function can return. .SS Signals .TP \f[B]void bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] An async-signal-safe function that can be called from a signal handler. If called from a signal handler on the same thread as any executing bcl(3) functions, it will interrupt the functions and force them to return early. It is undefined behavior if this function is called from a thread that is \f[I]not\f[R] executing any bcl(3) functions while any bcl(3) functions are executing. .RS .PP If execution \f[I]is\f[R] interrupted, \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] does \f[I]not\f[R] return to its caller. .PP See the \f[B]SIGNAL HANDLING\f[R] section. .RE .TP \f[B]bool bcl_running(\f[R]\f[I]void\f[R]\f[B])\f[R] An async-signal-safe function that can be called from a signal handler. It will return \f[B]true\f[R] if any bcl(3) procedures are running, which means it is safe to call \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R]. Otherwise, it returns \f[B]false\f[R]. .RS .PP See the \f[B]SIGNAL HANDLING\f[R] section. .RE .SS Setup .TP \f[B]BclError bcl_init(\f[R]\f[I]void\f[R]\f[B])\f[R] Initializes this library. This function can be called multiple times, but each call must be matched by a call to \f[B]bcl_free(\f[R]\f[I]void\f[R]\f[B])\f[R]. This is to make it possible for multiple libraries and applications to initialize bcl(3) without problem. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .PP This function must be the first one clients call. Calling any other function without calling this one first is undefined behavior. .RE .TP \f[B]void bcl_free(\f[R]\f[I]void\f[R]\f[B])\f[R] Decrements bcl(3)\[cq]s reference count and frees the data associated with it if the reference count is \f[B]0\f[R]. .RS .PP This function must be the last one clients call. Calling this function before calling any other function is undefined behavior. .RE .TP \f[B]bool bcl_abortOnFatalError(\f[R]\f[I]void\f[R]\f[B])\f[R] Queries and returns the current state of calling \f[B]abort()\f[R] on fatal errors. If \f[B]true\f[R] is returned, bcl(3) will cause a \f[B]SIGABRT\f[R] if a fatal error occurs. .RS .PP If activated, clients do not need to check for fatal errors. .RE .TP \f[B]void bcl_setAbortOnFatalError(bool\f[R] \f[I]abrt\f[R]\f[B])\f[R] Sets the state of calling \f[B]abort()\f[R] on fatal errors. If \f[I]abrt\f[R] is \f[B]false\f[R], bcl(3) will not cause a \f[B]SIGABRT\f[R] on fatal errors after the call. If \f[I]abrt\f[R] is \f[B]true\f[R], bcl(3) will cause a \f[B]SIGABRT\f[R] on fatal errors after the call. .RS .PP If activated, clients do not need to check for fatal errors. .RE .TP \f[B]void bcl_gc(\f[R]\f[I]void\f[R]\f[B])\f[R] Garbage collects cached instances of arbitrary-precision numbers. This only frees the memory of numbers that are \f[I]not\f[R] in use, so it is safe to call at any time. .SS Contexts .PP All procedures that take a \f[B]BclContext\f[R] parameter a require a valid context as an argument. .TP \f[B]struct BclCtxt\f[R] A forward declaration for a hidden \f[B]struct\f[R] type. Clients cannot access the internals of the \f[B]struct\f[R] type directly. All interactions with the type are done through pointers. See \f[B]BclContext\f[R] below. .TP \f[B]BclContext\f[R] A typedef to a pointer of \f[B]struct BclCtxt\f[R]. This is the only handle clients can get to \f[B]struct BclCtxt\f[R]. .RS .PP A \f[B]BclContext\f[R] contains the values \f[B]scale\f[R], \f[B]ibase\f[R], and \f[B]obase\f[R], as well as a list of numbers. .PP \f[B]scale\f[R] is a value used to control how many decimal places calculations should use. A value of \f[B]0\f[R] means that calculations are done on integers only, where applicable, and a value of 20, for example, means that all applicable calculations return results with 20 decimal places. The default is \f[B]0\f[R]. .PP \f[B]ibase\f[R] is a value used to control the input base. The minimum \f[B]ibase\f[R] is \f[B]2\f[R], and the maximum is \f[B]36\f[R]. If \f[B]ibase\f[R] is \f[B]2\f[R], numbers are parsed as though they are in binary, and any digits larger than \f[B]1\f[R] are clamped. Likewise, a value of \f[B]10\f[R] means that numbers are parsed as though they are decimal, and any larger digits are clamped. The default is \f[B]10\f[R]. .PP \f[B]obase\f[R] is a value used to control the output base. The minimum \f[B]obase\f[R] is \f[B]0\f[R] and the maximum is \f[B]BC_BASE_MAX\f[R] (see the \f[B]LIMITS\f[R] section). .PP Numbers created in one context are not valid in another context. It is undefined behavior to use a number created in a different context. Contexts are meant to isolate the numbers used by different clients in the same application. .RE .TP \f[B]BclContext bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B])\f[R] Creates a context and returns it. Returns \f[B]NULL\f[R] if there was an error. .TP \f[B]void bcl_ctxt_free(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Frees \f[I]ctxt\f[R], after which it is no longer valid. It is undefined behavior to attempt to use an invalid context. .TP \f[B]BclError bcl_pushContext(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Pushes \f[I]ctxt\f[R] onto bcl(3)\[cq]s stack of contexts. \f[I]ctxt\f[R] must have been created with \f[B]bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B])\f[R]. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .PP There \f[I]must\f[R] be a valid context to do any arithmetic. .RE .TP \f[B]void bcl_popContext(\f[R]\f[I]void\f[R]\f[B])\f[R] Pops the current context off of the stack, if one exists. .TP \f[B]BclContext bcl_context(\f[R]\f[I]void\f[R]\f[B])\f[R] Returns the current context, or \f[B]NULL\f[R] if no context exists. .TP \f[B]void bcl_ctxt_freeNums(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Frees all numbers in use that are associated with \f[I]ctxt\f[R]. It is undefined behavior to attempt to use a number associated with \f[I]ctxt\f[R] after calling this procedure unless such numbers have been created with \f[B]bcl_num_create(\f[R]\f[I]void\f[R]\f[B])\f[R] after calling this procedure. .TP \f[B]size_t bcl_ctxt_scale(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Returns the \f[B]scale\f[R] for given context. .TP \f[B]void bcl_ctxt_setScale(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B])\f[R] Sets the \f[B]scale\f[R] for the given context to the argument \f[I]scale\f[R]. .TP \f[B]size_t bcl_ctxt_ibase(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Returns the \f[B]ibase\f[R] for the given context. .TP \f[B]void bcl_ctxt_setIbase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]ibase\f[R]\f[B])\f[R] Sets the \f[B]ibase\f[R] for the given context to the argument \f[I]ibase\f[R]. If the argument \f[I]ibase\f[R] is invalid, it clamped, so an \f[I]ibase\f[R] of \f[B]0\f[R] or \f[B]1\f[R] is clamped to \f[B]2\f[R], and any values above \f[B]36\f[R] are clamped to \f[B]36\f[R]. .TP \f[B]size_t bcl_ctxt_obase(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Returns the \f[B]obase\f[R] for the given context. .TP \f[B]void bcl_ctxt_setObase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]obase\f[R]\f[B])\f[R] Sets the \f[B]obase\f[R] for the given context to the argument \f[I]obase\f[R]. .SS Errors .TP \f[B]BclError\f[R] An \f[B]enum\f[R] of possible error codes. See the \f[B]ERRORS\f[R] section for a complete listing the codes. .TP \f[B]BclError bcl_err(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Checks for errors in a \f[B]BclNumber\f[R]. All functions that can return a \f[B]BclNumber\f[R] can encode an error in the number, and this function will return the error, if any. If there was no error, it will return \f[B]BCL_ERROR_NONE\f[R]. .RS .PP There must be a valid current context. .RE .SS Numbers .PP All procedures in this section require a valid current context. .TP \f[B]BclNumber\f[R] A handle to an arbitrary-precision number. The actual number type is not exposed; the \f[B]BclNumber\f[R] handle is the only way clients can refer to instances of arbitrary-precision numbers. .TP \f[B]BclNumber bcl_num_create(\f[R]\f[I]void\f[R]\f[B])\f[R] Creates and returns a \f[B]BclNumber\f[R]. .RS .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]void bcl_num_free(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Frees \f[I]n\f[R]. It is undefined behavior to use \f[I]n\f[R] after calling this function. .TP \f[B]bool bcl_num_neg(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns \f[B]true\f[R] if \f[I]n\f[R] is negative, \f[B]false\f[R] otherwise. .TP \f[B]void bcl_num_setNeg(BclNumber\f[R] \f[I]n\f[R]\f[B], bool\f[R] \f[I]neg\f[R]\f[B])\f[R] Sets \f[I]n\f[R]\[cq]s sign to \f[I]neg\f[R], where \f[B]true\f[R] is negative, and \f[B]false\f[R] is positive. .TP \f[B]size_t bcl_num_scale(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns the \f[I]scale\f[R] of \f[I]n\f[R]. .RS .PP The \f[I]scale\f[R] of a number is the number of decimal places it has after the radix (decimal point). .RE .TP \f[B]BclError bcl_num_setScale(BclNumber\f[R] \f[I]n\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B])\f[R] Sets the \f[I]scale\f[R] of \f[I]n\f[R] to the argument \f[I]scale\f[R]. If the argument \f[I]scale\f[R] is greater than the \f[I]scale\f[R] of \f[I]n\f[R], \f[I]n\f[R] is extended. If the argument \f[I]scale\f[R] is less than the \f[I]scale\f[R] of \f[I]n\f[R], \f[I]n\f[R] is truncated. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]size_t bcl_num_len(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns the number of \f[I]significant decimal digits\f[R] in \f[I]n\f[R]. .SS Conversion .PP All procedures in this section require a valid current context. .PP All procedures in this section consume the given \f[B]BclNumber\f[R] arguments that are not given to pointer arguments. See the \f[B]Consumption and Propagation\f[R] subsection below. .TP \f[B]BclNumber bcl_parse(const char *restrict\f[R] \f[I]val\f[R]\f[B])\f[R] Parses a number string according to the current context\[cq]s \f[B]ibase\f[R] and returns the resulting number. .RS .PP \f[I]val\f[R] must be non-\f[B]NULL\f[R] and a valid string. See \f[B]BCL_ERROR_PARSE_INVALID_STR\f[R] in the \f[B]ERRORS\f[R] section for more information. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_PARSE_INVALID_STR\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]char* bcl_string(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns a string representation of \f[I]n\f[R] according the the current context\[cq]s \f[B]ibase\f[R]. The string is dynamically allocated and must be freed by the caller. .RS .PP \f[I]n\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .RE .TP \f[B]BclError bcl_bigdig(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig *\f[R]\f[I]result\f[R]\f[B])\f[R] Converts \f[I]n\f[R] into a \f[B]BclBigDig\f[R] and returns the result in the space pointed to by \f[I]result\f[R]. .RS .PP \f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R]. See the \f[B]LIMITS\f[R] section. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_OVERFLOW\f[R] .PP \f[I]n\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .RE .TP \f[B]BclNumber bcl_bigdig2num(BclBigDig\f[R] \f[I]val\f[R]\f[B])\f[R] Creates a \f[B]BclNumber\f[R] from \f[I]val\f[R]. .RS .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .SS Math .PP All procedures in this section require a valid current context. .PP All procedures in this section can return the following errors: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .TP \f[B]BclNumber bcl_add(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Adds \f[I]a\f[R] and \f[I]b\f[R] and returns the result. The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of \f[I]a\f[R] and \f[I]b\f[R]. .RS .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_sub(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Subtracts \f[I]b\f[R] from \f[I]a\f[R] and returns the result. The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of \f[I]a\f[R] and \f[I]b\f[R]. .RS .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_mul(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Multiplies \f[I]a\f[R] and \f[I]b\f[R] and returns the result. If \f[I]ascale\f[R] is the \f[I]scale\f[R] of \f[I]a\f[R] and \f[I]bscale\f[R] is the \f[I]scale\f[R] of \f[I]b\f[R], the \f[I]scale\f[R] of the result is equal to \f[B]min(ascale+bscale,max(scale,ascale,bscale))\f[R], where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .RS .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_div(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the result. The \f[I]scale\f[R] of the result is the \f[I]scale\f[R] of the current context. .RS .PP \f[I]b\f[R] cannot be \f[B]0\f[R]. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_mod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Divides \f[I]a\f[R] by \f[I]b\f[R] to the \f[I]scale\f[R] of the current context, computes the modulus \f[B]a-(a/b)*b\f[R], and returns the modulus. .RS .PP \f[I]b\f[R] cannot be \f[B]0\f[R]. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_pow(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Calculates \f[I]a\f[R] to the power of \f[I]b\f[R] to the \f[I]scale\f[R] of the current context. \f[I]b\f[R] must be an integer, but can be negative. If it is negative, \f[I]a\f[R] must be non-zero. .RS .PP \f[I]b\f[R] must be an integer. If \f[I]b\f[R] is negative, \f[I]a\f[R] must not be \f[B]0\f[R]. .PP \f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R]. See the \f[B]LIMITS\f[R] section. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_OVERFLOW\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_lshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Shifts \f[I]a\f[R] left (moves the radix right) by \f[I]b\f[R] places and returns the result. This is done in decimal. \f[I]b\f[R] must be an integer. .RS .PP \f[I]b\f[R] must be an integer. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_rshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Shifts \f[I]a\f[R] right (moves the radix left) by \f[I]b\f[R] places and returns the result. This is done in decimal. \f[I]b\f[R] must be an integer. .RS .PP \f[I]b\f[R] must be an integer. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_sqrt(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R] Calculates the square root of \f[I]a\f[R] and returns the result. The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the current context. .RS .PP \f[I]a\f[R] cannot be negative. .PP \f[I]a\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclError bcl_divmod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], BclNumber *\f[R]\f[I]d\f[R]\f[B])\f[R] Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the quotient in a new number which is put into the space pointed to by \f[I]c\f[R], and puts the modulus in a new number which is put into the space pointed to by \f[I]d\f[R]. .RS .PP \f[I]b\f[R] cannot be \f[B]0\f[R]. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]c\f[R] and \f[I]d\f[R] cannot point to the same place, nor can they point to the space occupied by \f[I]a\f[R] or \f[I]b\f[R]. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_modexp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B])\f[R] Computes a modular exponentiation where \f[I]a\f[R] is the base, \f[I]b\f[R] is the exponent, and \f[I]c\f[R] is the modulus, and returns the result. The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the current context. .RS .PP \f[I]a\f[R], \f[I]b\f[R], and \f[I]c\f[R] must be integers. \f[I]c\f[R] must not be \f[B]0\f[R]. \f[I]b\f[R] must not be negative. .PP \f[I]a\f[R], \f[I]b\f[R], and \f[I]c\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .SS Miscellaneous .TP \f[B]void bcl_zero(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Sets \f[I]n\f[R] to \f[B]0\f[R]. .TP \f[B]void bcl_one(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Sets \f[I]n\f[R] to \f[B]1\f[R]. .TP \f[B]ssize_t bcl_cmp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Compares \f[I]a\f[R] and \f[I]b\f[R] and returns \f[B]0\f[R] if \f[I]a\f[R] and \f[I]b\f[R] are equal, \f[B]<0\f[R] if \f[I]a\f[R] is less than \f[I]b\f[R], and \f[B]>0\f[R] if \f[I]a\f[R] is greater than \f[I]b\f[R]. .TP \f[B]BclError bcl_copy(BclNumber\f[R] \f[I]d\f[R]\f[B], BclNumber\f[R] \f[I]s\f[R]\f[B])\f[R] Copies \f[I]s\f[R] into \f[I]d\f[R]. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_dup(BclNumber\f[R] \f[I]s\f[R]\f[B])\f[R] Creates and returns a new \f[B]BclNumber\f[R] that is a copy of \f[I]s\f[R]. .RS .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .SS Pseudo-Random Number Generator .PP The pseudo-random number generator in bcl(3) is a \f[I]seeded\f[R] PRNG. Given the same seed twice, it will produce the same sequence of pseudo-random numbers twice. .PP By default, bcl(3) attempts to seed the PRNG with data from \f[B]/dev/urandom\f[R]. If that fails, it seeds itself with by calling \f[B]libc\f[R]\[cq]s \f[B]srand(time(NULL))\f[R] and then calling \f[B]rand()\f[R] for each byte, since \f[B]rand()\f[R] is only guaranteed to return \f[B]15\f[R] bits. .PP This should provide fairly good seeding in the standard case while also remaining fairly portable. .PP If necessary, the PRNG can be reseeded with one of the following functions: .IP \[bu] 2 \f[B]bcl_rand_seedWithNum(BclNumber)\f[R] .IP \[bu] 2 \f[B]bcl_rand_seed(unsigned char[BC_SEED_SIZE])\f[R] .IP \[bu] 2 \f[B]bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B])\f[R] .PP The following items allow clients to use the pseudo-random number generator. All procedures require a valid current context. .TP \f[B]BCL_SEED_ULONGS\f[R] The number of \f[B]unsigned long\f[R]\[cq]s in a seed for bcl(3)\[cq]s random number generator. .TP \f[B]BCL_SEED_SIZE\f[R] The size, in \f[B]char\f[R]\[cq]s, of a seed for bcl(3)\[cq]s random number generator. .TP \f[B]BclBigDig\f[R] bcl(3)\[cq]s overflow type (see the \f[B]PERFORMANCE\f[R] section). .TP \f[B]BclRandInt\f[R] An unsigned integer type returned by bcl(3)\[cq]s random number generator. .TP \f[B]BclNumber bcl_irand(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R] Returns a random number that is not larger than \f[I]a\f[R] in a new number. If \f[I]a\f[R] is \f[B]0\f[R] or \f[B]1\f[R], the new number is equal to \f[B]0\f[R]. The bound is unlimited, so it is not bound to the size of \f[B]BclRandInt\f[R]. This is done by generating as many random numbers as necessary, multiplying them by certain exponents, and adding them all together. .RS .PP \f[I]a\f[R] must be an integer and non-negative. .PP \f[I]a\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_frand(size_t\f[R] \f[I]places\f[R]\f[B])\f[R] Returns a random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) that has \f[I]places\f[R] decimal digits after the radix (decimal point). There are no limits on \f[I]places\f[R]. .RS .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_ifrand(BclNumber\f[R] \f[I]a\f[R]\f[B], size_t\f[R] \f[I]places\f[R]\f[B])\f[R] Returns a random number less than \f[I]a\f[R] with \f[I]places\f[R] decimal digits after the radix (decimal point). There are no limits on \f[I]a\f[R] or \f[I]places\f[R]. .RS .PP \f[I]a\f[R] must be an integer and non-negative. .PP \f[I]a\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclError bcl_rand_seedWithNum(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Seeds the PRNG with \f[I]n\f[R]. .RS .PP \f[I]n\f[R] is \f[I]not\f[R] consumed. .PP This procedure requires a valid current context. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .PP Note that if \f[B]bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B])\f[R] or \f[B]bcl_rand_seed2num_err(BclNumber)\f[R] are called right after this function, they are not guaranteed to return a number equal to \f[I]n\f[R]. .RE .TP \f[B]BclError bcl_rand_seed(unsigned char\f[R] \f[I]seed\f[R]\f[B][\f[R]\f[I]BC_SEED_SIZE\f[R]\f[B]])\f[R] Seeds the PRNG with the bytes in \f[I]seed\f[R]. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .RE .TP \f[B]void bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B])\f[R] Reseeds the PRNG with the default reseeding behavior. First, it attempts to read data from \f[B]/dev/urandom\f[R] and falls back to \f[B]libc\f[R]\[cq]s \f[B]rand()\f[R]. .RS .PP This procedure cannot fail. .RE .TP \f[B]BclNumber bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B])\f[R] Returns the current seed of the PRNG as a \f[B]BclNumber\f[R]. .RS .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclRandInt bcl_rand_int(\f[R]\f[I]void\f[R]\f[B])\f[R] Returns a random integer between \f[B]0\f[R] and \f[B]BC_RAND_MAX\f[R] (inclusive). .RS .PP This procedure cannot fail. .RE .TP \f[B]BclRandInt bcl_rand_bounded(BclRandInt\f[R] \f[I]bound\f[R]\f[B])\f[R] Returns a random integer between \f[B]0\f[R] and \f[I]bound\f[R] (exclusive). Bias is removed before returning the integer. .RS .PP This procedure cannot fail. .RE .SS Consumption and Propagation .PP Some functions are listed as consuming some or all of their arguments. This means that the arguments are freed, regardless of if there were errors or not. .PP This is to enable compact code like the following: .IP .nf \f[C] BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); \f[R] .fi .PP If arguments to those functions were not consumed, memory would be leaked until reclaimed with \f[B]bcl_ctxt_freeNums(BclContext)\f[R]. .PP When errors occur, they are propagated through. The result should always be checked with \f[B]bcl_err(BclNumber)\f[R], so the example above should properly be: .IP .nf \f[C] BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); if (bc_num_err(n) != BCL_ERROR_NONE) { // Handle the error. } \f[R] .fi .SH ERRORS .PP Most functions in bcl(3) return, directly or indirectly, any one of the error codes defined in \f[B]BclError\f[R]. The complete list of codes is the following: .TP \f[B]BCL_ERROR_NONE\f[R] Success; no error occurred. .TP \f[B]BCL_ERROR_INVALID_NUM\f[R] An invalid \f[B]BclNumber\f[R] was given as a parameter. .TP \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] An invalid \f[B]BclContext\f[R] is being used. .TP \f[B]BCL_ERROR_SIGNAL\f[R] A signal interrupted execution. .TP \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] A negative number was given as an argument to a parameter that cannot accept negative numbers, such as for square roots. .TP \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] A non-integer was given as an argument to a parameter that cannot accept non-integer numbers, such as for the second parameter of \f[B]bcl_num_pow()\f[R]. .TP \f[B]BCL_ERROR_MATH_OVERFLOW\f[R] A number that would overflow its result was given as an argument, such as for converting a \f[B]BclNumber\f[R] to a \f[B]BclBigDig\f[R]. .TP \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] A divide by zero occurred. .TP \f[B]BCL_ERROR_PARSE_INVALID_STR\f[R] An invalid number string was passed to a parsing function. .RS .PP A valid number string can only be one radix (period). In addition, any lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is allowed for the first character to be a dash. In that case, the number is considered to be negative. .PP There is one exception to the above: one lowercase \f[B]e\f[R] is allowed in the number, after the radix, if it exists. If the letter \f[B]e\f[R] exists, the number is considered to be in scientific notation, where the part before the \f[B]e\f[R] is the number, and the part after, which must be an integer, is the exponent. There can be a dash right after the \f[B]e\f[R] to indicate a negative exponent. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bcl(3) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bcl(3) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .RE .TP \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] bcl(3) failed to allocate memory. .RS .PP If clients call \f[B]bcl_setAbortOnFatalError()\f[R] with an \f[B]true\f[R] argument, this error will cause bcl(3) to throw a \f[B]SIGABRT\f[R]. This behavior can also be turned off later by calling that same function with a \f[B]false\f[R] argument. By default, this behavior is off. .PP It is highly recommended that client libraries do \f[I]not\f[R] activate this behavior. .RE .TP \f[B]BCL_ERROR_FATAL_UNKNOWN_ERR\f[R] An unknown error occurred. .RS .PP If clients call \f[B]bcl_setAbortOnFatalError()\f[R] with an \f[B]true\f[R] argument, this error will cause bcl(3) to throw a \f[B]SIGABRT\f[R]. This behavior can also be turned off later by calling that same function with a \f[B]false\f[R] argument. By default, this behavior is off. .PP It is highly recommended that client libraries do \f[I]not\f[R] activate this behavior. .RE .SH ATTRIBUTES .PP When \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] is used properly, bcl(3) is async-signal-safe. .PP bcl(3) is \f[I]MT-Unsafe\f[R]: it is unsafe to call any functions from more than one thread. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[R] types to calculate the value of \f[B]1\f[R] decimal digit at a time, but that can be slow. bcl(3) does something different. .PP It uses large integers to calculate more than \f[B]1\f[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP In addition, this bcl(3) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], 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 bcl(3): .TP \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] type in the environment where bcl(3) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] 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[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]bcl_rand_int()\f[R] function. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .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 SIGNAL HANDLING .PP If a signal handler calls \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] from the same thread that there are bcl(3) functions executing in, it will cause all execution to stop as soon as possible, interrupting long-running calculations, if necessary and cause the function that was executing to return. If possible, the error code \f[B]BC_ERROR_SIGNAL\f[R] is returned. .PP If execution \f[I]is\f[R] interrupted, \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] does \f[I]not\f[R] return to its caller. .PP It is undefined behavior if \f[B]bcl_handleSignal(\f[R]\f[I]void\f[R]\f[B])\f[R] is called from a thread that is not executing bcl(3) functions, if bcl(3) functions are executing. .SH SEE ALSO .PP bc(1) and dc(1) .SH STANDARDS .PP bcl(3) is compliant with the arithmetic defined in the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) specification for bc(1). .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. This is also true of bcl(3). .SH BUGS .PP None are known. Report bugs at https://git.yzena.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bcl.3.md b/contrib/bc/manuals/bcl.3.md index 1f515a39b221..76cd54de92a7 100644 --- a/contrib/bc/manuals/bcl.3.md +++ b/contrib/bc/manuals/bcl.3.md @@ -1,1177 +1,1177 @@ # NAME bcl - library of arbitrary precision decimal arithmetic # SYNOPSIS ## Use *#include * Link with *-lbcl*. ## Signals This procedure will allow clients to use signals to interrupt computations running in bcl(3). **void bcl_handleSignal(***void***);** **bool bcl_running(***void***);** ## Setup These items allow clients to set up bcl(3). **BclError bcl_init(***void***);** **void bcl_free(***void***);** **bool bcl_abortOnFatalError(***void***);** **void bcl_setAbortOnFatalError(bool** *abrt***);** **void bcl_gc(***void***);** ## Contexts These items will allow clients to handle contexts, which are isolated from each other. This allows more than one client to use bcl(3) in the same program. **struct BclCtxt;** **typedef struct BclCtxt\* BclContext;** **BclContext bcl_ctxt_create(***void***);** **void bcl_ctxt_free(BclContext** *ctxt***);** **BclError bcl_pushContext(BclContext** *ctxt***);** **void bcl_popContext(***void***);** **BclContext bcl_context(***void***);** **void bcl_ctxt_freeNums(BclContext** *ctxt***);** **size_t bcl_ctxt_scale(BclContext** *ctxt***);** **void bcl_ctxt_setScale(BclContext** *ctxt***, size_t** *scale***);** **size_t bcl_ctxt_ibase(BclContext** *ctxt***);** **void bcl_ctxt_setIbase(BclContext** *ctxt***, size_t** *ibase***);** **size_t bcl_ctxt_obase(BclContext** *ctxt***);** **void bcl_ctxt_setObase(BclContext** *ctxt***, size_t** *obase***);** ## Errors These items allow clients to handle errors. **typedef enum BclError BclError;** **BclError bcl_err(BclNumber** *n***);** ## Numbers These items allow clients to manipulate and query the arbitrary-precision numbers managed by bcl(3). **typedef struct { size_t i; } BclNumber;** **BclNumber bcl_num_create(***void***);** **void bcl_num_free(BclNumber** *n***);** **bool bcl_num_neg(BclNumber** *n***);** **void bcl_num_setNeg(BclNumber** *n***, bool** *neg***);** **size_t bcl_num_scale(BclNumber** *n***);** **BclError bcl_num_setScale(BclNumber** *n***, size_t** *scale***);** **size_t bcl_num_len(BclNumber** *n***);** ## Conversion These items allow clients to convert numbers into and from strings and integers. **BclNumber bcl_parse(const char \*restrict** *val***);** **char\* bcl_string(BclNumber** *n***);** **BclError bcl_bigdig(BclNumber** *n***, BclBigDig \****result***);** **BclNumber bcl_bigdig2num(BclBigDig** *val***);** ## Math These items allow clients to run math on numbers. **BclNumber bcl_add(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_sub(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_mul(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_div(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_mod(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_pow(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_lshift(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_rshift(BclNumber** *a***, BclNumber** *b***);** **BclNumber bcl_sqrt(BclNumber** *a***);** **BclError bcl_divmod(BclNumber** *a***, BclNumber** *b***, BclNumber \****c***, BclNumber \****d***);** **BclNumber bcl_modexp(BclNumber** *a***, BclNumber** *b***, BclNumber** *c***);** ## Miscellaneous These items are miscellaneous. **void bcl_zero(BclNumber** *n***);** **void bcl_one(BclNumber** *n***);** **ssize_t bcl_cmp(BclNumber** *a***, BclNumber** *b***);** **BclError bcl_copy(BclNumber** *d***, BclNumber** *s***);** **BclNumber bcl_dup(BclNumber** *s***);** ## Pseudo-Random Number Generator These items allow clients to manipulate the seeded pseudo-random number generator in bcl(3). **#define BCL_SEED_ULONGS** **#define BCL_SEED_SIZE** **typedef unsigned long BclBigDig;** **typedef unsigned long BclRandInt;** **BclNumber bcl_irand(BclNumber** *a***);** **BclNumber bcl_frand(size_t** *places***);** **BclNumber bcl_ifrand(BclNumber** *a***, size_t** *places***);** **BclError bcl_rand_seedWithNum(BclNumber** *n***);** **BclError bcl_rand_seed(unsigned char** *seed***[***BC_SEED_SIZE***]);** **void bcl_rand_reseed(***void***);** **BclNumber bcl_rand_seed2num(***void***);** **BclRandInt bcl_rand_int(***void***);** **BclRandInt bcl_rand_bounded(BclRandInt** *bound***);** # DESCRIPTION bcl(3) is a library that implements arbitrary-precision decimal math, as [standardized by POSIX][1] in bc(1). bcl(3) is async-signal-safe if **bcl_handleSignal(***void***)** is used properly. (See the **SIGNAL HANDLING** section.) All of the items in its interface are described below. See the documentation for each function for what each function can return. ## Signals **void bcl_handleSignal(***void***)** : An async-signal-safe function that can be called from a signal handler. If called from a signal handler on the same thread as any executing bcl(3) functions, it will interrupt the functions and force them to return early. It is undefined behavior if this function is called from a thread that is *not* executing any bcl(3) functions while any bcl(3) functions are executing. If execution *is* interrupted, **bcl_handleSignal(***void***)** does *not* return to its caller. See the **SIGNAL HANDLING** section. **bool bcl_running(***void***)** : An async-signal-safe function that can be called from a signal handler. It will return **true** if any bcl(3) procedures are running, which means it is safe to call **bcl_handleSignal(***void***)**. Otherwise, it returns **false**. See the **SIGNAL HANDLING** section. ## Setup **BclError bcl_init(***void***)** : Initializes this library. This function can be called multiple times, but each call must be matched by a call to **bcl_free(***void***)**. This is to make it possible for multiple libraries and applications to initialize bcl(3) without problem. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_FATAL_ALLOC_ERR** This function must be the first one clients call. Calling any other function without calling this one first is undefined behavior. **void bcl_free(***void***)** : Decrements bcl(3)'s reference count and frees the data associated with it if the reference count is **0**. This function must be the last one clients call. Calling this function before calling any other function is undefined behavior. **bool bcl_abortOnFatalError(***void***)** : Queries and returns the current state of calling **abort()** on fatal errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal error occurs. If activated, clients do not need to check for fatal errors. **void bcl_setAbortOnFatalError(bool** *abrt***)** : Sets the state of calling **abort()** on fatal errors. If *abrt* is **false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors after the call. If activated, clients do not need to check for fatal errors. **void bcl_gc(***void***)** : Garbage collects cached instances of arbitrary-precision numbers. This only frees the memory of numbers that are *not* in use, so it is safe to call at any time. ## Contexts All procedures that take a **BclContext** parameter a require a valid context as an argument. **struct BclCtxt** : A forward declaration for a hidden **struct** type. Clients cannot access the internals of the **struct** type directly. All interactions with the type are done through pointers. See **BclContext** below. **BclContext** : A typedef to a pointer of **struct BclCtxt**. This is the only handle clients can get to **struct BclCtxt**. A **BclContext** contains the values **scale**, **ibase**, and **obase**, as well as a list of numbers. **scale** is a value used to control how many decimal places calculations should use. A value of **0** means that calculations are done on integers only, where applicable, and a value of 20, for example, means that all applicable calculations return results with 20 decimal places. The default is **0**. **ibase** is a value used to control the input base. The minimum **ibase** is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are parsed as though they are in binary, and any digits larger than **1** are clamped. Likewise, a value of **10** means that numbers are parsed as though they are decimal, and any larger digits are clamped. The default is **10**. **obase** is a value used to control the output base. The minimum **obase** is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section). Numbers created in one context are not valid in another context. It is undefined behavior to use a number created in a different context. Contexts are meant to isolate the numbers used by different clients in the same application. **BclContext bcl_ctxt_create(***void***)** : Creates a context and returns it. Returns **NULL** if there was an error. **void bcl_ctxt_free(BclContext** *ctxt***)** : Frees *ctxt*, after which it is no longer valid. It is undefined behavior to attempt to use an invalid context. **BclError bcl_pushContext(BclContext** *ctxt***)** : Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created with **bcl_ctxt_create(***void***)**. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_FATAL_ALLOC_ERR** There *must* be a valid context to do any arithmetic. **void bcl_popContext(***void***)** : Pops the current context off of the stack, if one exists. **BclContext bcl_context(***void***)** : Returns the current context, or **NULL** if no context exists. **void bcl_ctxt_freeNums(BclContext** *ctxt***)** : Frees all numbers in use that are associated with *ctxt*. It is undefined behavior to attempt to use a number associated with *ctxt* after calling this procedure unless such numbers have been created with **bcl_num_create(***void***)** after calling this procedure. **size_t bcl_ctxt_scale(BclContext** *ctxt***)** : Returns the **scale** for given context. **void bcl_ctxt_setScale(BclContext** *ctxt***, size_t** *scale***)** : Sets the **scale** for the given context to the argument *scale*. **size_t bcl_ctxt_ibase(BclContext** *ctxt***)** : Returns the **ibase** for the given context. **void bcl_ctxt_setIbase(BclContext** *ctxt***, size_t** *ibase***)** : Sets the **ibase** for the given context to the argument *ibase*. If the argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is clamped to **2**, and any values above **36** are clamped to **36**. **size_t bcl_ctxt_obase(BclContext** *ctxt***)** : Returns the **obase** for the given context. **void bcl_ctxt_setObase(BclContext** *ctxt***, size_t** *obase***)** : Sets the **obase** for the given context to the argument *obase*. ## Errors **BclError** : An **enum** of possible error codes. See the **ERRORS** section for a complete listing the codes. **BclError bcl_err(BclNumber** *n***)** : Checks for errors in a **BclNumber**. All functions that can return a **BclNumber** can encode an error in the number, and this function will return the error, if any. If there was no error, it will return **BCL_ERROR_NONE**. There must be a valid current context. ## Numbers All procedures in this section require a valid current context. **BclNumber** : A handle to an arbitrary-precision number. The actual number type is not exposed; the **BclNumber** handle is the only way clients can refer to instances of arbitrary-precision numbers. **BclNumber bcl_num_create(***void***)** : Creates and returns a **BclNumber**. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **void bcl_num_free(BclNumber** *n***)** : Frees *n*. It is undefined behavior to use *n* after calling this function. **bool bcl_num_neg(BclNumber** *n***)** : Returns **true** if *n* is negative, **false** otherwise. **void bcl_num_setNeg(BclNumber** *n***, bool** *neg***)** : Sets *n*'s sign to *neg*, where **true** is negative, and **false** is positive. **size_t bcl_num_scale(BclNumber** *n***)** : Returns the *scale* of *n*. The *scale* of a number is the number of decimal places it has after the radix (decimal point). **BclError bcl_num_setScale(BclNumber** *n***, size_t** *scale***)** : Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is greater than the *scale* of *n*, *n* is extended. If the argument *scale* is less than the *scale* of *n*, *n* is truncated. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **size_t bcl_num_len(BclNumber** *n***)** : Returns the number of *significant decimal digits* in *n*. ## Conversion All procedures in this section require a valid current context. All procedures in this section consume the given **BclNumber** arguments that are not given to pointer arguments. See the **Consumption and Propagation** subsection below. **BclNumber bcl_parse(const char \*restrict** *val***)** : Parses a number string according to the current context's **ibase** and returns the resulting number. *val* must be non-**NULL** and a valid string. See **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more information. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_PARSE_INVALID_STR** * **BCL_ERROR_FATAL_ALLOC_ERR** **char\* bcl_string(BclNumber** *n***)** : Returns a string representation of *n* according the the current context's **ibase**. The string is dynamically allocated and must be freed by the caller. *n* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. **BclError bcl_bigdig(BclNumber** *n***, BclBigDig \****result***)** : Converts *n* into a **BclBigDig** and returns the result in the space pointed to by *result*. *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_OVERFLOW** *n* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. **BclNumber bcl_bigdig2num(BclBigDig** *val***)** : Creates a **BclNumber** from *val*. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** ## Math All procedures in this section require a valid current context. All procedures in this section can return the following errors: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_add(BclNumber** *a***, BclNumber** *b***)** : Adds *a* and *b* and returns the result. The *scale* of the result is the max of the *scale*s of *a* and *b*. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_sub(BclNumber** *a***, BclNumber** *b***)** : Subtracts *b* from *a* and returns the result. The *scale* of the result is the max of the *scale*s of *a* and *b*. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_mul(BclNumber** *a***, BclNumber** *b***)** : Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and **max()** return the obvious values. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_div(BclNumber** *a***, BclNumber** *b***)** : Divides *a* by *b* and returns the result. The *scale* of the result is the *scale* of the current context. *b* cannot be **0**. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_mod(BclNumber** *a***, BclNumber** *b***)** : Divides *a* by *b* to the *scale* of the current context, computes the modulus **a-(a/b)\*b**, and returns the modulus. *b* cannot be **0**. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_pow(BclNumber** *a***, BclNumber** *b***)** : Calculates *a* to the power of *b* to the *scale* of the current context. *b* must be an integer, but can be negative. If it is negative, *a* must be non-zero. *b* must be an integer. If *b* is negative, *a* must not be **0**. *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_NON_INTEGER** - * **BCL_ERROR_MATH_OVERFLOW** - * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_MATH_OVERFLOW** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_lshift(BclNumber** *a***, BclNumber** *b***)** : Shifts *a* left (moves the radix right) by *b* places and returns the result. This is done in decimal. *b* must be an integer. *b* must be an integer. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_rshift(BclNumber** *a***, BclNumber** *b***)** : Shifts *a* right (moves the radix left) by *b* places and returns the result. This is done in decimal. *b* must be an integer. *b* must be an integer. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_sqrt(BclNumber** *a***)** : Calculates the square root of *a* and returns the result. The *scale* of the result is equal to the **scale** of the current context. *a* cannot be negative. *a* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclError bcl_divmod(BclNumber** *a***, BclNumber** *b***, BclNumber \****c***, BclNumber \****d***)** : Divides *a* by *b* and returns the quotient in a new number which is put into the space pointed to by *c*, and puts the modulus in a new number which is put into the space pointed to by *d*. - *b* cannot be **0**. + *b* cannot be **0**. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *c* and *d* cannot point to the same place, nor can they point to the space occupied by *a* or *b*. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_modexp(BclNumber** *a***, BclNumber** *b***, BclNumber** *c***)** : Computes a modular exponentiation where *a* is the base, *b* is the exponent, and *c* is the modulus, and returns the result. The *scale* of the result is equal to the **scale** of the current context. *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be negative. *a*, *b*, and *c* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_NEGATIVE** - * **BCL_ERROR_MATH_NON_INTEGER** - * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** ## Miscellaneous **void bcl_zero(BclNumber** *n***)** : Sets *n* to **0**. **void bcl_one(BclNumber** *n***)** : Sets *n* to **1**. **ssize_t bcl_cmp(BclNumber** *a***, BclNumber** *b***)** : Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if *a* is less than *b*, and **>0** if *a* is greater than *b*. **BclError bcl_copy(BclNumber** *d***, BclNumber** *s***)** : Copies *s* into *d*. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_dup(BclNumber** *s***)** : Creates and returns a new **BclNumber** that is a copy of *s*. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** ## Pseudo-Random Number Generator The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same seed twice, it will produce the same sequence of pseudo-random numbers twice. By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and then calling **rand()** for each byte, since **rand()** is only guaranteed to return **15** bits. This should provide fairly good seeding in the standard case while also remaining fairly portable. If necessary, the PRNG can be reseeded with one of the following functions: * **bcl_rand_seedWithNum(BclNumber)** * **bcl_rand_seed(unsigned char[BC_SEED_SIZE])** * **bcl_rand_reseed(***void***)** The following items allow clients to use the pseudo-random number generator. All procedures require a valid current context. **BCL_SEED_ULONGS** : The number of **unsigned long**'s in a seed for bcl(3)'s random number generator. **BCL_SEED_SIZE** : The size, in **char**'s, of a seed for bcl(3)'s random number generator. **BclBigDig** : bcl(3)'s overflow type (see the **PERFORMANCE** section). **BclRandInt** : An unsigned integer type returned by bcl(3)'s random number generator. **BclNumber bcl_irand(BclNumber** *a***)** : Returns a random number that is not larger than *a* in a new number. If *a* is **0** or **1**, the new number is equal to **0**. The bound is unlimited, so it is not bound to the size of **BclRandInt**. This is done by generating as many random numbers as necessary, multiplying them by certain exponents, and adding them all together. *a* must be an integer and non-negative. *a* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_NEGATIVE** - * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_frand(size_t** *places***)** : Returns a random number between **0** (inclusive) and **1** (exclusive) that has *places* decimal digits after the radix (decimal point). There are no limits on *places*. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_ifrand(BclNumber** *a***, size_t** *places***)** : Returns a random number less than *a* with *places* decimal digits after the radix (decimal point). There are no limits on *a* or *places*. *a* must be an integer and non-negative. *a* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** - * **BCL_ERROR_MATH_NEGATIVE** - * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclError bcl_rand_seedWithNum(BclNumber** *n***)** : Seeds the PRNG with *n*. *n* is *not* consumed. This procedure requires a valid current context. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** Note that if **bcl_rand_seed2num(***void***)** or **bcl_rand_seed2num_err(BclNumber)** are called right after this function, they are not guaranteed to return a number equal to *n*. **BclError bcl_rand_seed(unsigned char** *seed***[***BC_SEED_SIZE***])** : Seeds the PRNG with the bytes in *seed*. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** **void bcl_rand_reseed(***void***)** : Reseeds the PRNG with the default reseeding behavior. First, it attempts to read data from **/dev/urandom** and falls back to **libc**'s **rand()**. This procedure cannot fail. **BclNumber bcl_rand_seed2num(***void***)** : Returns the current seed of the PRNG as a **BclNumber**. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: - * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclRandInt bcl_rand_int(***void***)** : Returns a random integer between **0** and **BC_RAND_MAX** (inclusive). This procedure cannot fail. **BclRandInt bcl_rand_bounded(BclRandInt** *bound***)** : Returns a random integer between **0** and *bound* (exclusive). Bias is removed before returning the integer. This procedure cannot fail. ## Consumption and Propagation Some functions are listed as consuming some or all of their arguments. This means that the arguments are freed, regardless of if there were errors or not. This is to enable compact code like the following: BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); If arguments to those functions were not consumed, memory would be leaked until reclaimed with **bcl_ctxt_freeNums(BclContext)**. When errors occur, they are propagated through. The result should always be checked with **bcl_err(BclNumber)**, so the example above should properly be: BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); if (bc_num_err(n) != BCL_ERROR_NONE) { // Handle the error. } # ERRORS Most functions in bcl(3) return, directly or indirectly, any one of the error codes defined in **BclError**. The complete list of codes is the following: **BCL_ERROR_NONE** : Success; no error occurred. **BCL_ERROR_INVALID_NUM** : An invalid **BclNumber** was given as a parameter. **BCL_ERROR_INVALID_CONTEXT** : An invalid **BclContext** is being used. **BCL_ERROR_SIGNAL** : A signal interrupted execution. **BCL_ERROR_MATH_NEGATIVE** : A negative number was given as an argument to a parameter that cannot accept negative numbers, such as for square roots. **BCL_ERROR_MATH_NON_INTEGER** : A non-integer was given as an argument to a parameter that cannot accept non-integer numbers, such as for the second parameter of **bcl_num_pow()**. **BCL_ERROR_MATH_OVERFLOW** : A number that would overflow its result was given as an argument, such as for converting a **BclNumber** to a **BclBigDig**. **BCL_ERROR_MATH_DIVIDE_BY_ZERO** : A divide by zero occurred. **BCL_ERROR_PARSE_INVALID_STR** : An invalid number string was passed to a parsing function. A valid number string can only be one radix (period). In addition, any lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is allowed for the first character to be a dash. In that case, the number is considered to be negative. There is one exception to the above: one lowercase **e** is allowed in the number, after the radix, if it exists. If the letter **e** exists, the number is considered to be in scientific notation, where the part before the **e** is the number, and the part after, which must be an integer, is the exponent. There can be a dash right after the **e** to indicate a negative exponent. **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 bcl(3) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bcl(3) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. **BCL_ERROR_FATAL_ALLOC_ERR** : bcl(3) failed to allocate memory. If clients call **bcl_setAbortOnFatalError()** with an **true** argument, this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also be turned off later by calling that same function with a **false** argument. By default, this behavior is off. It is highly recommended that client libraries do *not* activate this behavior. **BCL_ERROR_FATAL_UNKNOWN_ERR** : An unknown error occurred. If clients call **bcl_setAbortOnFatalError()** with an **true** argument, this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also be turned off later by calling that same function with a **false** argument. By default, this behavior is off. It is highly recommended that client libraries do *not* activate this behavior. # ATTRIBUTES When **bcl_handleSignal(***void***)** is used properly, bcl(3) is async-signal-safe. bcl(3) is *MT-Unsafe*: it is unsafe to call any functions from more than one thread. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. bcl(3) 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**. In addition, this bcl(3) 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 bcl(3): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bcl(3) 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_SCALE_MAX** : The maximum **scale**. 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 **bcl_rand_int()** function. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. 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. # SIGNAL HANDLING If a signal handler calls **bcl_handleSignal(***void***)** from the same thread that there are bcl(3) functions executing in, it will cause all execution to stop as soon as possible, interrupting long-running calculations, if necessary and cause the function that was executing to return. If possible, the error code **BC_ERROR_SIGNAL** is returned. If execution *is* interrupted, **bcl_handleSignal(***void***)** does *not* return to its caller. It is undefined behavior if **bcl_handleSignal(***void***)** is called from a thread that is not executing bcl(3) functions, if bcl(3) functions are executing. # SEE ALSO bc(1) and dc(1) # STANDARDS bcl(3) is compliant with the arithmetic defined in the [IEEE Std 1003.1-2017 (“POSIX.1-2017”)][1] specification for bc(1). 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 is also true of bcl(3). # 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 diff --git a/contrib/bc/manuals/dc.1.md.in b/contrib/bc/manuals/dc.1.md.in index b00eff17471e..c5c361fe271a 100644 --- a/contrib/bc/manuals/dc.1.md.in +++ b/contrib/bc/manuals/dc.1.md.in @@ -1,1270 +1,1270 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. {{ 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/A.1 b/contrib/bc/manuals/dc/A.1 index 2fc16a5b8b73..7b91c02039e4 100644 --- a/contrib/bc/manuals/dc/A.1 +++ b/contrib/bc/manuals/dc/A.1 @@ -1,1351 +1,1350 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/A.1.md b/contrib/bc/manuals/dc/A.1.md index 0c4fd2b9ef13..e53646c2fba3 100644 --- a/contrib/bc/manuals/dc/A.1.md +++ b/contrib/bc/manuals/dc/A.1.md @@ -1,1207 +1,1207 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/E.1 b/contrib/bc/manuals/dc/E.1 index 54b77232d76e..ebe8db87e996 100644 --- a/contrib/bc/manuals/dc/E.1 +++ b/contrib/bc/manuals/dc/E.1 @@ -1,1143 +1,1142 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/E.1.md b/contrib/bc/manuals/dc/E.1.md index b7cc625df362..5e0a85af9a90 100644 --- a/contrib/bc/manuals/dc/E.1.md +++ b/contrib/bc/manuals/dc/E.1.md @@ -1,1040 +1,1040 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/EH.1 b/contrib/bc/manuals/dc/EH.1 index 986e686239e4..e8e4b9069506 100644 --- a/contrib/bc/manuals/dc/EH.1 +++ b/contrib/bc/manuals/dc/EH.1 @@ -1,1128 +1,1127 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/EH.1.md b/contrib/bc/manuals/dc/EH.1.md index 0f6df3e6f474..6d1413d0dae4 100644 --- a/contrib/bc/manuals/dc/EH.1.md +++ b/contrib/bc/manuals/dc/EH.1.md @@ -1,1027 +1,1027 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/EHN.1 b/contrib/bc/manuals/dc/EHN.1 index 0b8d34cfa25f..37f4a6656c65 100644 --- a/contrib/bc/manuals/dc/EHN.1 +++ b/contrib/bc/manuals/dc/EHN.1 @@ -1,1124 +1,1123 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/EHN.1.md b/contrib/bc/manuals/dc/EHN.1.md index 361d641b50b2..2e24a10a06dc 100644 --- a/contrib/bc/manuals/dc/EHN.1.md +++ b/contrib/bc/manuals/dc/EHN.1.md @@ -1,1022 +1,1022 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/EHNP.1 b/contrib/bc/manuals/dc/EHNP.1 index c4e2acf5544e..f0ea848f819b 100644 --- a/contrib/bc/manuals/dc/EHNP.1 +++ b/contrib/bc/manuals/dc/EHNP.1 @@ -1,1117 +1,1116 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/EHNP.1.md b/contrib/bc/manuals/dc/EHNP.1.md index acbd58e543dc..5abed62294c2 100644 --- a/contrib/bc/manuals/dc/EHNP.1.md +++ b/contrib/bc/manuals/dc/EHNP.1.md @@ -1,1017 +1,1017 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/EHP.1 b/contrib/bc/manuals/dc/EHP.1 index 2ac14f02bf45..654c24309c56 100644 --- a/contrib/bc/manuals/dc/EHP.1 +++ b/contrib/bc/manuals/dc/EHP.1 @@ -1,1121 +1,1120 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/EHP.1.md b/contrib/bc/manuals/dc/EHP.1.md index 982570c9c999..17ebe0420492 100644 --- a/contrib/bc/manuals/dc/EHP.1.md +++ b/contrib/bc/manuals/dc/EHP.1.md @@ -1,1022 +1,1022 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/EN.1 b/contrib/bc/manuals/dc/EN.1 index c38435ea86d8..6d522efdde45 100644 --- a/contrib/bc/manuals/dc/EN.1 +++ b/contrib/bc/manuals/dc/EN.1 @@ -1,1139 +1,1138 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/EN.1.md b/contrib/bc/manuals/dc/EN.1.md index 4df214965ac5..4c0297fdab7f 100644 --- a/contrib/bc/manuals/dc/EN.1.md +++ b/contrib/bc/manuals/dc/EN.1.md @@ -1,1035 +1,1035 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/ENP.1 b/contrib/bc/manuals/dc/ENP.1 index aea2ec6a6c39..c9659423dc26 100644 --- a/contrib/bc/manuals/dc/ENP.1 +++ b/contrib/bc/manuals/dc/ENP.1 @@ -1,1132 +1,1131 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/ENP.1.md b/contrib/bc/manuals/dc/ENP.1.md index f88b418e3bfe..4025c643b956 100644 --- a/contrib/bc/manuals/dc/ENP.1.md +++ b/contrib/bc/manuals/dc/ENP.1.md @@ -1,1030 +1,1030 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/EP.1 b/contrib/bc/manuals/dc/EP.1 index 1e16db4a3d47..1dd0da3235e7 100644 --- a/contrib/bc/manuals/dc/EP.1 +++ b/contrib/bc/manuals/dc/EP.1 @@ -1,1136 +1,1135 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]2\f[R]. Values are output in the specified base. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .SH COMMANDS .PP The valid commands are listed below. .SS Printing .PP These commands are used for printing. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], and \f[B]scale\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]2\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]) operator. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/EP.1.md b/contrib/bc/manuals/dc/EP.1.md index a64d49b13433..fcb15291262d 100644 --- a/contrib/bc/manuals/dc/EP.1.md +++ b/contrib/bc/manuals/dc/EP.1.md @@ -1,1035 +1,1035 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/H.1 b/contrib/bc/manuals/dc/H.1 index 5c09b430db8e..15fe0edb0d2d 100644 --- a/contrib/bc/manuals/dc/H.1 +++ b/contrib/bc/manuals/dc/H.1 @@ -1,1336 +1,1335 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/H.1.md b/contrib/bc/manuals/dc/H.1.md index aff75f379e10..de83e3088f9c 100644 --- a/contrib/bc/manuals/dc/H.1.md +++ b/contrib/bc/manuals/dc/H.1.md @@ -1,1194 +1,1194 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/HN.1 b/contrib/bc/manuals/dc/HN.1 index 38efef021c64..a617bb473ec1 100644 --- a/contrib/bc/manuals/dc/HN.1 +++ b/contrib/bc/manuals/dc/HN.1 @@ -1,1332 +1,1331 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/HN.1.md b/contrib/bc/manuals/dc/HN.1.md index 6248037980d9..005579cd02c8 100644 --- a/contrib/bc/manuals/dc/HN.1.md +++ b/contrib/bc/manuals/dc/HN.1.md @@ -1,1189 +1,1189 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/HNP.1 b/contrib/bc/manuals/dc/HNP.1 index bb103564f3ca..7eb4b8b19f3d 100644 --- a/contrib/bc/manuals/dc/HNP.1 +++ b/contrib/bc/manuals/dc/HNP.1 @@ -1,1325 +1,1324 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/HNP.1.md b/contrib/bc/manuals/dc/HNP.1.md index 54d5957b6d93..d099d6f9cdcf 100644 --- a/contrib/bc/manuals/dc/HNP.1.md +++ b/contrib/bc/manuals/dc/HNP.1.md @@ -1,1184 +1,1184 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/HP.1 b/contrib/bc/manuals/dc/HP.1 index abbf1b24da1d..cea646c8a3f3 100644 --- a/contrib/bc/manuals/dc/HP.1 +++ b/contrib/bc/manuals/dc/HP.1 @@ -1,1329 +1,1328 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/HP.1.md b/contrib/bc/manuals/dc/HP.1.md index 25e690f6f0e5..93938790f460 100644 --- a/contrib/bc/manuals/dc/HP.1.md +++ b/contrib/bc/manuals/dc/HP.1.md @@ -1,1189 +1,1189 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/N.1 b/contrib/bc/manuals/dc/N.1 index e257c79bc9b7..6f4f01c48354 100644 --- a/contrib/bc/manuals/dc/N.1 +++ b/contrib/bc/manuals/dc/N.1 @@ -1,1347 +1,1346 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] Disables the prompt in TTY mode. (The prompt is only enabled in TTY mode. See the \f[B]TTY MODE\f[R] 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[R]. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/N.1.md b/contrib/bc/manuals/dc/N.1.md index 1d9d1d6f64ed..43876cfb24a6 100644 --- a/contrib/bc/manuals/dc/N.1.md +++ b/contrib/bc/manuals/dc/N.1.md @@ -1,1202 +1,1202 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-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** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/NP.1 b/contrib/bc/manuals/dc/NP.1 index 7c799d0ee25b..ad4a69957c1c 100644 --- a/contrib/bc/manuals/dc/NP.1 +++ b/contrib/bc/manuals/dc/NP.1 @@ -1,1340 +1,1339 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/NP.1.md b/contrib/bc/manuals/dc/NP.1.md index 60cc89078876..b1f29d76f06e 100644 --- a/contrib/bc/manuals/dc/NP.1.md +++ b/contrib/bc/manuals/dc/NP.1.md @@ -1,1197 +1,1197 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/dc/P.1 b/contrib/bc/manuals/dc/P.1 index b28e0dadda48..2bbe54c37604 100644 --- a/contrib/bc/manuals/dc/P.1 +++ b/contrib/bc/manuals/dc/P.1 @@ -1,1344 +1,1343 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2021 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" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" .SH Name .PP dc - arbitrary-precision decimal reverse-Polish notation calculator .SH SYNOPSIS .PP -\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]\[en]version\f[R]] -[\f[B]\[en]help\f[R]] [\f[B]\[en]interactive\f[R]] -[\f[B]\[en]no-prompt\f[R]] [\f[B]\[en]extended-register\f[R]] -[\f[B]-e\f[R] \f[I]expr\f[R]] -[\f[B]\[en]expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] -\f[I]file\f[R]\&...] [\f[B]-file\f[R]=\f[I]file\f[R]\&...] +\f[B]dc\f[R] [\f[B]-hiPvVx\f[R]] [\f[B]--version\f[R]] +[\f[B]--help\f[R]] [\f[B]--interactive\f[R]] [\f[B]--no-prompt\f[R]] +[\f[B]--extended-register\f[R]] [\f[B]-e\f[R] \f[I]expr\f[R]] +[\f[B]--expression\f[R]=\f[I]expr\f[R]\&...] [\f[B]-f\f[R] +\f[I]file\f[R]\&...] [\f[B]--file\f[R]=\f[I]file\f[R]\&...] [\f[I]file\f[R]\&...] .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[R] or \f[B]\[en]file\f[R] arguments), then dc(1) reads from +as \f[B]-f\f[R] or \f[B]--file\f[R] arguments), then dc(1) reads from \f[B]stdin\f[R]. 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[R] (\f[B]\[en]expression\f[R]) and -\f[B]-f\f[R] (\f[B]\[en]file\f[R]) arguments cause dc(1) to execute them +implementations, where \f[B]-e\f[R] (\f[B]--expression\f[R]) and +\f[B]-f\f[R] (\f[B]--file\f[R]) 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[R] (see the \f[B]ENVIRONMENT VARIABLES\f[R] 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[R] always set to \f[B]10\f[R], they can set \f[B]DC_ENV_ARGS\f[R] to \f[B]-e 10k\f[R], and this dc(1) will always start with a \f[B]scale\f[R] of \f[B]10\f[R]. .PP If users want to have dc(1) exit after processing all input from \f[B]-e\f[R] and \f[B]-f\f[R] arguments (and their equivalents), then they can just simply add \f[B]-e q\f[R] as the last command-line argument or define the environment variable \f[B]DC_EXPR_EXIT\f[R]. .SH OPTIONS .PP The following are the options that dc(1) accepts. .TP -\f[B]-h\f[R], \f[B]\[en]help\f[R] +\f[B]-h\f[R], \f[B]--help\f[R] Prints a usage message and quits. .TP -\f[B]-v\f[R], \f[B]-V\f[R], \f[B]\[en]version\f[R] +\f[B]-v\f[R], \f[B]-V\f[R], \f[B]--version\f[R] Print the version information (copyright header) and exit. .TP -\f[B]-i\f[R], \f[B]\[en]interactive\f[R] +\f[B]-i\f[R], \f[B]--interactive\f[R] Forces interactive mode. (See the \f[B]INTERACTIVE MODE\f[R] section.) .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-P\f[R], \f[B]\[en]no-prompt\f[R] +\f[B]-P\f[R], \f[B]--no-prompt\f[R] This option is a no-op. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-x\f[R] \f[B]\[en]extended-register\f[R] +\f[B]-x\f[R] \f[B]--extended-register\f[R] Enables extended register mode. See the \f[I]Extended Register Mode\f[R] subsection of the \f[B]REGISTERS\f[R] section for more information. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-e\f[R] \f[I]expr\f[R], \f[B]\[en]expression\f[R]=\f[I]expr\f[R] +\f[B]-e\f[R] \f[I]expr\f[R], \f[B]--expression\f[R]=\f[I]expr\f[R] Evaluates \f[I]expr\f[R]. 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 If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R], whether on the command-line or in +\f[B]-f\f[R] or \f[B]--file\f[R], whether on the command-line or in \f[B]DC_ENV_ARGS\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP -\f[B]-f\f[R] \f[I]file\f[R], \f[B]\[en]file\f[R]=\f[I]file\f[R] +\f[B]-f\f[R] \f[I]file\f[R], \f[B]--file\f[R]=\f[I]file\f[R] Reads in \f[I]file\f[R] and evaluates it, line by line, as though it were read through \f[B]stdin\f[R]. If expressions are also given (see above), the expressions are evaluated in the order given. .RS .PP If this option is given on the command-line (i.e., not in \f[B]DC_ENV_ARGS\f[R], see the \f[B]ENVIRONMENT VARIABLES\f[R] section), then after processing all expressions and files, dc(1) will exit, unless \f[B]-\f[R] (\f[B]stdin\f[R]) was given as an argument at least once to -\f[B]-f\f[R] or \f[B]\[en]file\f[R]. -However, if any other \f[B]-e\f[R], \f[B]\[en]expression\f[R], -\f[B]-f\f[R], or \f[B]\[en]file\f[R] arguments are given after +\f[B]-f\f[R] or \f[B]--file\f[R]. +However, if any other \f[B]-e\f[R], \f[B]--expression\f[R], +\f[B]-f\f[R], or \f[B]--file\f[R] arguments are given after \f[B]-f-\f[R] or equivalent is given, dc(1) will give a fatal error and exit. .PP This is a \f[B]non-portable extension\f[R]. .RE .PP All long options are \f[B]non-portable extensions\f[R]. .SH STDOUT .PP Any non-error output is written to \f[B]stdout\f[R]. In addition, if history (see the \f[B]HISTORY\f[R] section) and the prompt (see the \f[B]TTY MODE\f[R] section) are enabled, both are output to \f[B]stdout\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stdout\f[R], so if \f[B]stdout\f[R] is closed, as in \f[B]dc >&-\f[R], it will quit with an error. This is done so that dc(1) can report problems when \f[B]stdout\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH STDERR .PP Any error output is written to \f[B]stderr\f[R]. .PP \f[B]Note\f[R]: Unlike other dc(1) implementations, this dc(1) will issue a fatal error (see the \f[B]EXIT STATUS\f[R] section) if it cannot write to \f[B]stderr\f[R], so if \f[B]stderr\f[R] is closed, as in \f[B]dc 2>&-\f[R], it will quit with an error. This is done so that dc(1) can exit with an error code when \f[B]stderr\f[R] 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[R] to \f[B]/dev/null\f[R]. .SH SYNTAX .PP Each item in the input source code, either a number (see the \f[B]NUMBERS\f[R] section) or a command (see the \f[B]COMMANDS\f[R] section), is processed and executed, in order. Input is processed immediately when entered. .PP \f[B]ibase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to interpret constant numbers. It is the \[lq]input\[rq] base, or the number base used for interpreting input numbers. \f[B]ibase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]ibase\f[R] is \f[B]16\f[R]. The min allowable value for \f[B]ibase\f[R] is \f[B]2\f[R]. The max allowable value for \f[B]ibase\f[R] can be queried in dc(1) programs with the \f[B]T\f[R] command. .PP \f[B]obase\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that determines how to output results. It is the \[lq]output\[rq] base, or the number base used for outputting numbers. \f[B]obase\f[R] is initially \f[B]10\f[R]. The max allowable value for \f[B]obase\f[R] is \f[B]DC_BASE_MAX\f[R] and can be queried with the \f[B]U\f[R] command. The min allowable value for \f[B]obase\f[R] is \f[B]0\f[R]. If \f[B]obase\f[R] is \f[B]0\f[R], values are output in scientific notation, and if \f[B]obase\f[R] is \f[B]1\f[R], 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[R]. .PP The \f[I]scale\f[R] of an expression is the number of digits in the result of the expression right of the decimal point, and \f[B]scale\f[R] is a register (see the \f[B]REGISTERS\f[R] section) that sets the precision of any operations (with exceptions). \f[B]scale\f[R] is initially \f[B]0\f[R]. \f[B]scale\f[R] cannot be negative. The max allowable value for \f[B]scale\f[R] can be queried in dc(1) programs with the \f[B]V\f[R] command. .PP \f[B]seed\f[R] is a register containing the current seed for the pseudo-random number generator. If the current value of \f[B]seed\f[R] is queried and stored, then if it is assigned to \f[B]seed\f[R] 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[R] was first queried. .PP Multiple values assigned to \f[B]seed\f[R] can produce the same sequence of pseudo-random numbers. Likewise, when a value is assigned to \f[B]seed\f[R], it is not guaranteed that querying \f[B]seed\f[R] immediately after will return the same value. In addition, the value of \f[B]seed\f[R] will change after any call to the \f[B]\[cq]\f[R] command or the \f[B]\[dq]\f[R] command that does not get receive a value of \f[B]0\f[R] or \f[B]1\f[R]. The maximum integer returned by the \f[B]\[cq]\f[R] command can be queried with the \f[B]W\f[R] command. .PP \f[B]Note\f[R]: The values returned by the pseudo-random number generator with the \f[B]\[cq]\f[R] and \f[B]\[dq]\f[R] commands are guaranteed to \f[B]NOT\f[R] be cryptographically secure. This is a consequence of using a seeded pseudo-random number generator. However, they \f[I]are\f[R] guaranteed to be reproducible with identical \f[B]seed\f[R] values. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is \f[I]ESSENTIAL\f[R]. In any other case, use a non-seeded pseudo-random number generator. .PP The pseudo-random number generator, \f[B]seed\f[R], and all associated operations are \f[B]non-portable extensions\f[R]. .SS Comments .PP Comments go from \f[B]#\f[R] until, and not including, the next newline. This is a \f[B]non-portable extension\f[R]. .SH NUMBERS .PP Numbers are strings made up of digits, uppercase letters up to \f[B]F\f[R], and at most \f[B]1\f[R] period for a radix. Numbers can have up to \f[B]DC_NUM_MAX\f[R] digits. Uppercase letters are equal to \f[B]9\f[R] + their position in the alphabet (i.e., \f[B]A\f[R] equals \f[B]10\f[R], or \f[B]9+1\f[R]). If a digit or letter makes no sense with the current value of \f[B]ibase\f[R], they are set to the value of the highest valid digit in \f[B]ibase\f[R]. .PP Single-character numbers (i.e., \f[B]A\f[R] alone) take the value that they would have if they were valid digits, regardless of the value of \f[B]ibase\f[R]. This means that \f[B]A\f[R] alone always equals decimal \f[B]10\f[R] and \f[B]F\f[R] alone always equals decimal \f[B]15\f[R]. .PP In addition, dc(1) accepts numbers in scientific notation. These have the form \f[B]e\f[R]. The exponent (the portion after the \f[B]e\f[R]) must be an integer. An example is \f[B]1.89237e9\f[R], which is equal to \f[B]1892370000\f[R]. Negative exponents are also allowed, so \f[B]4.2890e_3\f[R] is equal to \f[B]0.0042890\f[R]. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and dc(1) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if dc(1) is given the number string \f[B]10e_4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .PP Accepting input as scientific notation is a \f[B]non-portable extension\f[R]. .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[R] to \f[B]obase\f[R] using \f[B]0o\f[R], and engineering notation is activated by assigning \f[B]1\f[R] to \f[B]obase\f[R] using \f[B]1o\f[R]. To deactivate them, just assign a different value to \f[B]obase\f[R]. .PP Printing numbers in scientific notation and/or engineering notation is a \f[B]non-portable extension\f[R]. .TP \f[B]p\f[R] 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 \f[B]n\f[R] Prints the value on top of the stack, whether number or string, and pops it off of the stack. .TP \f[B]P\f[R] 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[R] is \f[B]UCHAR_MAX+1\f[R] 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[R]. .RE .TP \f[B]f\f[R] 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 \f[B]+\f[R] The top two values are popped off the stack, added, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]-\f[R] The top two values are popped off the stack, subtracted, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to the max \f[I]scale\f[R] of both operands. .TP \f[B]*\f[R] The top two values are popped off the stack, multiplied, and the result is pushed onto the stack. If \f[B]a\f[R] is the \f[I]scale\f[R] of the first expression and \f[B]b\f[R] is the \f[I]scale\f[R] of the second expression, the \f[I]scale\f[R] of the result is equal to \f[B]min(a+b,max(scale,a,b))\f[R] where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .TP \f[B]/\f[R] The top two values are popped off the stack, divided, and the result is pushed onto the stack. The \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]%\f[R] 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[R] to current \f[B]scale\f[R], and 2) Using the result of step 1 to calculate \f[B]a-(a/b)*b\f[R] to \f[I]scale\f[R] \f[B]max(scale+scale(b),scale(a))\f[R]. .PP The first value popped off of the stack must be non-zero. .RE .TP \f[B]\[ti]\f[R] 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[R] except that \f[B]x\f[R] and \f[B]y\f[R] 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[R]. .RE .TP \f[B]\[ha]\f[R] 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 \f[I]scale\f[R] of the result is equal to \f[B]scale\f[R]. .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 \f[B]v\f[R] 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[R] of the result is equal to \f[B]scale\f[R]. .RS .PP The value popped off of the stack must be non-negative. .RE .TP \f[B]_\f[R] If this command \f[I]immediately\f[R] 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[R]. .RE .TP \f[B]b\f[R] 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[R]. .RE .TP \f[B]|\f[R] 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[R]. .RE .TP \f[B]$\f[R] 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[R]. .RE .TP \f[B]\[at]\f[R] 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[R]. .RE .TP \f[B]H\f[R] 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[R]. .RE .TP \f[B]h\f[R] 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[R]. .RE .TP \f[B]G\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if they are equal, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]N\f[R] The top value is popped off of the stack, and if it a \f[B]0\f[R], a \f[B]1\f[R] is pushed; otherwise, a \f[B]0\f[R] is pushed. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B](\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]{\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is less than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B])\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]}\f[R] The top two values are popped off of the stack, they are compared, and a \f[B]1\f[R] is pushed if the first is greater than or equal to the second, or \f[B]0\f[R] otherwise. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]M\f[R] The top two values are popped off of the stack. If they are both non-zero, a \f[B]1\f[R] is pushed onto the stack. If either of them is zero, or both of them are, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]&&\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]m\f[R] The top two values are popped off of the stack. If at least one of them is non-zero, a \f[B]1\f[R] is pushed onto the stack. If both of them are zero, then a \f[B]0\f[R] is pushed onto the stack. .RS .PP This is like the \f[B]||\f[R] operator in bc(1), and it is \f[I]not\f[R] a short-circuit operator. .PP This is a \f[B]non-portable extension\f[R]. .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[R] value that controls the pseudo-random number generator.) .PP The pseudo-random number generator is guaranteed to \f[B]NOT\f[R] be cryptographically secure. .TP \f[B]\[cq]\f[R] Generates an integer between 0 and \f[B]DC_RAND_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] 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[R]. .RE .TP \f[B]\[dq]\f[R] Pops a value off of the stack, which is used as an \f[B]exclusive\f[R] 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[R] section) while \f[B]seed\f[R] remains unchanged. If the bound is larger than \f[B]DC_RAND_MAX\f[R], the higher bound is honored by generating several pseudo-random integers, multiplying them by appropriate powers of \f[B]DC_RAND_MAX+1\f[R], 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[R], unless the operand is \f[B]0\f[R] or \f[B]1\f[R]. In that case, \f[B]0\f[R] is pushed onto the stack, and \f[B]seed\f[R] is \f[I]not\f[R] 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[R]. .RE .SS Stack Control .PP These commands control the stack. .TP \f[B]c\f[R] Removes all items from (\[lq]clears\[rq]) the stack. .TP \f[B]d\f[R] Copies the item on top of the stack (\[lq]duplicates\[rq]) and pushes the copy onto the stack. .TP \f[B]r\f[R] Swaps (\[lq]reverses\[rq]) the two top items on the stack. .TP \f[B]R\f[R] Pops (\[lq]removes\[rq]) the top value from the stack. .SS Register Control .PP These commands control registers (see the \f[B]REGISTERS\f[R] section). .TP \f[B]s\f[R]\f[I]r\f[R] Pops the value off the top of the stack and stores it into register \f[I]r\f[R]. .TP \f[B]l\f[R]\f[I]r\f[R] Copies the value in register \f[I]r\f[R] and pushes it onto the stack. This does not alter the contents of \f[I]r\f[R]. .TP \f[B]S\f[R]\f[I]r\f[R] Pops the value off the top of the (main) stack and pushes it onto the stack of register \f[I]r\f[R]. The previous value of the register becomes inaccessible. .TP \f[B]L\f[R]\f[I]r\f[R] Pops the value off the top of the stack for register \f[I]r\f[R] and push it onto the main stack. The previous value in the stack for register \f[I]r\f[R], if any, is now accessible via the \f[B]l\f[R]\f[I]r\f[R] command. .SS Parameters .PP These commands control the values of \f[B]ibase\f[R], \f[B]obase\f[R], \f[B]scale\f[R], and \f[B]seed\f[R]. Also see the \f[B]SYNTAX\f[R] section. .TP \f[B]i\f[R] Pops the value off of the top of the stack and uses it to set \f[B]ibase\f[R], which must be between \f[B]2\f[R] and \f[B]16\f[R], inclusive. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]o\f[R] Pops the value off of the top of the stack and uses it to set \f[B]obase\f[R], which must be between \f[B]0\f[R] and \f[B]DC_BASE_MAX\f[R], inclusive (see the \f[B]LIMITS\f[R] section and the \f[B]NUMBERS\f[R] section). .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]k\f[R] Pops the value off of the top of the stack and uses it to set \f[B]scale\f[R], which must be non-negative. .RS .PP If the value on top of the stack has any \f[I]scale\f[R], the \f[I]scale\f[R] is ignored. .RE .TP \f[B]j\f[R] Pops the value off of the top of the stack and uses it to set \f[B]seed\f[R]. The meaning of \f[B]seed\f[R] 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[R] and sign of the value may be significant. .PP If a previously used \f[B]seed\f[R] 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[R] value was previously used. .PP The exact value assigned to \f[B]seed\f[R] is not guaranteed to be returned if the \f[B]J\f[R] command is used. However, if \f[B]seed\f[R] \f[I]does\f[R] return a different value, both values, when assigned to \f[B]seed\f[R], are guaranteed to produce the same sequence of pseudo-random numbers. This means that certain values assigned to \f[B]seed\f[R] 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[R] of the value that can be assigned to \f[B]seed\f[R]. .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]I\f[R] Pushes the current value of \f[B]ibase\f[R] onto the main stack. .TP \f[B]O\f[R] Pushes the current value of \f[B]obase\f[R] onto the main stack. .TP \f[B]K\f[R] Pushes the current value of \f[B]scale\f[R] onto the main stack. .TP \f[B]J\f[R] Pushes the current value of \f[B]seed\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]T\f[R] Pushes the maximum allowable value of \f[B]ibase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]U\f[R] Pushes the maximum allowable value of \f[B]obase\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]V\f[R] Pushes the maximum allowable value of \f[B]scale\f[R] onto the main stack. .RS .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]W\f[R] Pushes the maximum (inclusive) integer that can be generated with the \f[B]\[cq]\f[R] pseudo-random number generator command. .RS .PP This is a \f[B]non-portable extension\f[R]. .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[R] 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[R] is executed as a macro, then the code \f[B]1pR\f[R] is executed, meaning that the \f[B]1\f[R] will be printed with a newline after and then popped from the stack. .TP \f[B][\f[R]_characters_\f[B]]\f[R] Makes a string containing \f[I]characters\f[R] and pushes it onto the stack. .RS .PP If there are brackets (\f[B][\f[R] and \f[B]]\f[R]) in the string, then they must be balanced. Unbalanced brackets can be escaped using a backslash (\f[B]\[rs]\f[R]) 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 \f[B]a\f[R] 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[R] is calculated. If that result is \f[B]0\f[R], 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[R]. .RE .TP \f[B]x\f[R] 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 \f[B]>\f[R]\f[I]r\f[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 \f[I]r\f[R] are executed. .RS .PP For example, \f[B]0 1>a\f[R] will execute the contents of register \f[B]a\f[R], and \f[B]1 0>a\f[R] 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[R] section). .RE .TP \f[B]>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!>\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!>\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!<\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!<\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]!=\f[R]\f[I]r\f[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 \f[I]r\f[R] 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[R] section). .RE .TP \f[B]!=\f[R]\f[I]r\f[R]\f[B]e\f[R]\f[I]s\f[R] Like the above, but will execute register \f[I]s\f[R] 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[R] section). .PP This is a \f[B]non-portable extension\f[R]. .RE .TP \f[B]?\f[R] Reads a line from the \f[B]stdin\f[R] and executes it. This is to allow macros to request input from users. .TP \f[B]q\f[R] 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. .TP \f[B]Q\f[R] 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. .SS Status .PP These commands query status of the stack or its top value. .TP \f[B]Z\f[R] 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 \f[B]X\f[R] Pops a value off of the stack. .RS .PP If it is a number, pushes the \f[I]scale\f[R] of the value onto the stack. .PP If it is a string, pushes \f[B]0\f[R]. .RE .TP \f[B]z\f[R] Pushes the current stack depth (before execution of this command). .SS Arrays .PP These commands manipulate arrays. .TP \f[B]:\f[R]\f[I]r\f[R] Pops the top two values off of the stack. The second value will be stored in the array \f[I]r\f[R] (see the \f[B]REGISTERS\f[R] section), indexed by the first value. .TP \f[B];\f[R]\f[I]r\f[R] Pops the value on top of the stack and uses it as an index into the array \f[I]r\f[R]. The selected value is then pushed onto the stack. .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[R]) 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]`\[rs]n'\f[R]); 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[R] or -\f[B]\[en]extended-register\f[R] command-line arguments are given), then +\f[B]--extended-register\f[R] command-line arguments are given), then normal single character registers are used \f[I]unless\f[R] the character immediately following a command that needs a register name is a space (according to \f[B]isspace()\f[R]) and not a newline (\f[B]`\[rs]n'\f[R]). .PP In that case, the register name is found according to the regex \f[B][a-z][a-z0-9_]*\f[R] (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[R] 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[R] types to calculate the value of \f[B]1\f[R] 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[R] decimal digit at a time. If built in a environment where \f[B]DC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]DC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]DC_BASE_DIGS\f[R]. .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[R], 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 \f[B]DC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] 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[R] section). .TP \f[B]DC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]DC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]DC_BASE_DIGS\f[R]. .TP \f[B]DC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]DC_LONG_BIT\f[R]. .TP \f[B]DC_BASE_MAX\f[R] The maximum output base. Set at \f[B]DC_BASE_POW\f[R]. .TP \f[B]DC_DIM_MAX\f[R] The maximum size of arrays. Set at \f[B]SIZE_MAX-1\f[R]. .TP \f[B]DC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_STRING_MAX\f[R] The maximum length of strings. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NAME_MAX\f[R] The maximum length of identifiers. Set at \f[B]DC_OVERFLOW_MAX-1\f[R]. .TP \f[B]DC_NUM_MAX\f[R] 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[R]. .TP \f[B]DC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]\[cq]\f[R] command, if dc(1). Set at \f[B]2\[ha]DC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]DC_OVERFLOW_MAX\f[R]. .TP Number of vars The maximum number of vars/arrays. Set at \f[B]SIZE_MAX-1\f[R]. .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 \f[B]DC_ENV_ARGS\f[R] 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[R] will be processed before arguments and files given on the command-line. This gives the user the ability to set up \[lq]standard\[rq] 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[R] option to set \f[B]scale\f[R] to a value other than \f[B]0\f[R]. .RS .PP The code that parses \f[B]DC_ENV_ARGS\f[R] will correctly handle quoted arguments, but it does not understand escape sequences. For example, the string \f[B]\[lq]/home/gavin/some dc file.dc\[rq]\f[R] will be correctly parsed, but the string \f[B]\[lq]/home/gavin/some \[dq]dc\[dq] file.dc\[rq]\f[R] will include the backslashes. .PP The quote parsing will handle either kind of quotes, \f[B]\[cq]\f[R] or \f[B]\[lq]\f[R]. 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]\[rq]some `dc' file.dc\[dq]\f[R], 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[R] 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 \f[B]DC_LINE_LENGTH\f[R] If this environment variable exists and contains an integer that is greater than \f[B]1\f[R] and is less than \f[B]UINT16_MAX\f[R] (\f[B]2\[ha]16-1\f[R]), dc(1) will output lines to that length, including the backslash newline combo. The default line length is \f[B]70\f[R]. .TP \f[B]DC_EXPR_EXIT\f[R] 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[R] and/or \f[B]-f\f[R] command-line options (and any equivalents). .SH EXIT STATUS .PP dc(1) returns the following exit statuses: .TP \f[B]0\f[R] No error. .TP \f[B]1\f[R] A math error occurred. This follows standard practice of using \f[B]1\f[R] 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[R], 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]\[ha]\f[R]), places (\f[B]\[at]\f[R]), left shift (\f[B]H\f[R]), and right shift (\f[B]h\f[R]) operators. .RE .TP \f[B]2\f[R] A parse error occurred. .RS .PP Parse errors include unexpected \f[B]EOF\f[R], using an invalid character, failing to find the end of a string or comment, and using a token where it is invalid. .RE .TP \f[B]3\f[R] A runtime error occurred. .RS .PP Runtime errors include assigning an invalid number to \f[B]ibase\f[R], \f[B]obase\f[R], or \f[B]scale\f[R]; give a bad expression to a \f[B]read()\f[R] call, calling \f[B]read()\f[R] inside of a \f[B]read()\f[R] call, type errors, and attempting an operation when the stack has too few elements. .RE .TP \f[B]4\f[R] 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[R] is special; when a fatal error occurs, dc(1) always exits and returns \f[B]4\f[R], 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[R] section), since dc(1) resets its state (see the \f[B]RESET\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] flag or \f[B]\[en]interactive\f[R] option. +\f[B]-i\f[R] flag or \f[B]--interactive\f[R] 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[R] and \f[B]stdout\f[R] are hooked to a terminal, but the \f[B]-i\f[R] flag -and \f[B]\[en]interactive\f[R] option can turn it on in other cases. +and \f[B]--interactive\f[R] 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[R] section), and in normal execution, flushes \f[B]stdout\f[R] as soon as execution is done for the current input. .SH TTY MODE .PP If \f[B]stdin\f[R], \f[B]stdout\f[R], and \f[B]stderr\f[R] are all connected to a TTY, dc(1) turns on \[lq]TTY mode.\[rq] .PP TTY mode is required for history to be enabled (see the \f[B]COMMAND LINE HISTORY\f[R] section). It is also required to enable special handling for \f[B]SIGINT\f[R] 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[R] and \f[B]stdout\f[R] to be connected to a terminal. .SH SIGNAL HANDLING .PP Sending a \f[B]SIGINT\f[R] 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[R] section), it will reset (see the \f[B]RESET\f[R] section). Otherwise, it will clean up and exit. .PP Note that \[lq]current input\[rq] can mean one of two things. If dc(1) is processing input from \f[B]stdin\f[R] 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[R] if no other file exists. .PP This means that if a \f[B]SIGINT\f[R] 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[R] and \f[B]SIGQUIT\f[R] 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[R]; in that case, when dc(1) is in TTY mode, a \f[B]SIGHUP\f[R] 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[R] section), history is enabled. Previous lines can be recalled and edited with the arrow keys. .PP \f[B]Note\f[R]: 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[R]. .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 (\[lq]POSIX.1-2017\[rq]) (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. diff --git a/contrib/bc/manuals/dc/P.1.md b/contrib/bc/manuals/dc/P.1.md index 396a9873c517..0101b68fb872 100644 --- a/contrib/bc/manuals/dc/P.1.md +++ b/contrib/bc/manuals/dc/P.1.md @@ -1,1202 +1,1202 @@ # Name dc - arbitrary-precision decimal reverse-Polish notation calculator # SYNOPSIS -**dc** [**-hiPvVx**] [**--version**] [**--help**] [**--interactive**] [**--no-prompt**] [**--extended-register**] [**-e** *expr*] [**--expression**=*expr*...] [**-f** *file*...] [**-file**=*file*...] [*file*...] +**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, +**-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**) +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** +**-h**, **-\-help** : Prints a usage message and quits. -**-v**, **-V**, **--version** +**-v**, **-V**, **-\-version** : Print the version information (copyright header) and exit. -**-i**, **--interactive** +**-i**, **-\-interactive** : Forces interactive mode. (See the **INTERACTIVE MODE** section.) This is a **non-portable extension**. -**-P**, **--no-prompt** +**-P**, **-\-no-prompt** : This option is a no-op. This is a **non-portable extension**. -**-x** **--extended-register** +**-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* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**, whether on the + as an argument at least once to **-f** or **-\-file**, whether on the command-line or in **DC_ENV_ARGS**. However, if any other **-e**, - **--expression**, **-f**, or **--file** arguments are given after **-f-** or - equivalent is given, dc(1) will give a fatal error and exit. + **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** + or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. -**-f** *file*, **--file**=*file* +**-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. If this option is given on the command-line (i.e., not in **DC_ENV_ARGS**, see the **ENVIRONMENT VARIABLES** section), then after processing all expressions and files, dc(1) will exit, unless **-** (**stdin**) was given - as an argument at least once to **-f** or **--file**. However, if any other - **-e**, **--expression**, **-f**, or **--file** arguments are given after + as an argument at least once to **-f** or **-\-file**. However, if any other + **-e**, **-\-expression**, **-f**, or **-\-file** arguments are given after **-f-** or equivalent is given, dc(1) will give a fatal error and exit. This is a **non-portable extension**. All long options are **non-portable extensions**. # STDOUT Any non-error output is written to **stdout**. In addition, if history (see the **HISTORY** section) and the prompt (see the **TTY MODE** section) are enabled, both are output to **stdout**. **Note**: Unlike 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. This means that the pseudo-random values from dc(1) should only be used where a reproducible stream of pseudo-random numbers is *ESSENTIAL*. In any other case, use a non-seeded pseudo-random number generator. The pseudo-random number generator, **seed**, and all associated operations are **non-portable extensions**. ## Comments Comments go from **#** until, and not including, the next newline. This is a **non-portable extension**. # NUMBERS Numbers are strings made up of digits, uppercase letters up to **F**, and at most **1** period for a radix. Numbers can have up to **DC_NUM_MAX** digits. Uppercase letters are equal to **9** + 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 exponent (the portion after the **e**) must be an integer. An example is **1.89237e9**, which is equal to **1892370000**. Negative exponents are also allowed, so **4.2890e_3** is equal to **0.0042890**. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the 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 *scale* of the result is equal to **scale**. 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** +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 'dc' file.dc"**, 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. +**-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** 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 +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 diff --git a/contrib/bc/manuals/header_bc.txt b/contrib/bc/manuals/header_bc.txt index 91e60bd4a984..e07d2e79a1ce 100644 --- a/contrib/bc/manuals/header_bc.txt +++ b/contrib/bc/manuals/header_bc.txt @@ -1 +1 @@ -.TH "BC" "1" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "BC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" diff --git a/contrib/bc/manuals/header_bcl.txt b/contrib/bc/manuals/header_bcl.txt index 290cc7794143..5933f01f2732 100644 --- a/contrib/bc/manuals/header_bcl.txt +++ b/contrib/bc/manuals/header_bcl.txt @@ -1 +1 @@ -.TH "BCL" "3" "February 2021" "Gavin D. Howard" "Libraries Manual" +.TH "BCL" "3" "March 2021" "Gavin D. Howard" "Libraries Manual" diff --git a/contrib/bc/manuals/header_dc.txt b/contrib/bc/manuals/header_dc.txt index 787d492b3066..227aac310a0e 100644 --- a/contrib/bc/manuals/header_dc.txt +++ b/contrib/bc/manuals/header_dc.txt @@ -1 +1 @@ -.TH "DC" "1" "February 2021" "Gavin D. Howard" "General Commands Manual" +.TH "DC" "1" "March 2021" "Gavin D. Howard" "General Commands Manual" diff --git a/contrib/bc/src/num.c b/contrib/bc/src/num.c index 158e06a68875..6131034ac535 100644 --- a/contrib/bc/src/num.c +++ b/contrib/bc/src/num.c @@ -1,2971 +1,2971 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 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 the number type. * */ #include #include #include #include #include #include #include #include #include #include static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale); static inline ssize_t bc_num_neg(size_t n, bool neg) { return (((ssize_t) n) ^ -((ssize_t) neg)) + neg; } ssize_t bc_num_cmpZero(const BcNum *n) { return bc_num_neg((n)->len != 0, BC_NUM_NEG(n)); } static inline size_t bc_num_int(const BcNum *n) { return n->len ? n->len - BC_NUM_RDX_VAL(n) : 0; } static void bc_num_expand(BcNum *restrict n, size_t req) { assert(n != NULL); req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE; if (req > n->cap) { BC_SIG_LOCK; n->num = bc_vm_realloc(n->num, BC_NUM_SIZE(req)); n->cap = req; BC_SIG_UNLOCK; } } static void bc_num_setToZero(BcNum *restrict n, size_t scale) { assert(n != NULL); n->scale = scale; n->len = n->rdx = 0; } void bc_num_zero(BcNum *restrict n) { bc_num_setToZero(n, 0); } void bc_num_one(BcNum *restrict n) { bc_num_zero(n); n->len = 1; n->num[0] = 1; } static void bc_num_clean(BcNum *restrict n) { while (BC_NUM_NONZERO(n) && !n->num[n->len - 1]) n->len -= 1; if (BC_NUM_ZERO(n)) n->rdx = 0; else { size_t rdx = BC_NUM_RDX_VAL(n); if (n->len < rdx) n->len = rdx; } } static size_t bc_num_log10(size_t i) { size_t len; for (len = 1; i; i /= BC_BASE, ++len); assert(len - 1 <= BC_BASE_DIGS + 1); return len - 1; } static inline size_t bc_num_zeroDigits(const BcDig *n) { assert(*n >= 0); assert(((size_t) *n) < BC_BASE_POW); return BC_BASE_DIGS - bc_num_log10((size_t) *n); } static size_t bc_num_intDigits(const BcNum *n) { size_t digits = bc_num_int(n) * BC_BASE_DIGS; if (digits > 0) digits -= bc_num_zeroDigits(n->num + n->len - 1); return digits; } static size_t bc_num_nonzeroLen(const BcNum *restrict n) { size_t i, len = n->len; assert(len == BC_NUM_RDX_VAL(n)); for (i = len - 1; i < len && !n->num[i]; --i); assert(i + 1 > 0); return i + 1; } static BcDig bc_num_addDigits(BcDig a, BcDig b, bool *carry) { assert(((BcBigDig) BC_BASE_POW) * 2 == ((BcDig) BC_BASE_POW) * 2); assert(a < BC_BASE_POW); assert(b < BC_BASE_POW); a += b + *carry; *carry = (a >= BC_BASE_POW); if (*carry) a -= BC_BASE_POW; assert(a >= 0); assert(a < BC_BASE_POW); return a; } static BcDig bc_num_subDigits(BcDig a, BcDig b, bool *carry) { assert(a < BC_BASE_POW); assert(b < BC_BASE_POW); b += *carry; *carry = (a < b); if (*carry) a += BC_BASE_POW; assert(a - b >= 0); assert(a - b < BC_BASE_POW); return a - b; } static void bc_num_addArrays(BcDig *restrict a, const BcDig *restrict b, size_t len) { size_t i; bool carry = false; for (i = 0; i < len; ++i) a[i] = bc_num_addDigits(a[i], b[i], &carry); for (; carry; ++i) a[i] = bc_num_addDigits(a[i], 0, &carry); } static void bc_num_subArrays(BcDig *restrict a, const BcDig *restrict b, size_t len) { size_t i; bool carry = false; for (i = 0; i < len; ++i) a[i] = bc_num_subDigits(a[i], b[i], &carry); for (; carry; ++i) a[i] = bc_num_subDigits(a[i], 0, &carry); } static void bc_num_mulArray(const BcNum *restrict a, BcBigDig b, BcNum *restrict c) { size_t i; BcBigDig carry = 0; assert(b <= BC_BASE_POW); if (a->len + 1 > c->cap) bc_num_expand(c, a->len + 1); memset(c->num, 0, BC_NUM_SIZE(c->cap)); for (i = 0; i < a->len; ++i) { BcBigDig in = ((BcBigDig) a->num[i]) * b + carry; c->num[i] = in % BC_BASE_POW; carry = in / BC_BASE_POW; } assert(carry < BC_BASE_POW); c->num[i] = (BcDig) carry; c->len = a->len; c->len += (carry != 0); bc_num_clean(c); assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); } static void bc_num_divArray(const BcNum *restrict a, BcBigDig b, BcNum *restrict c, BcBigDig *rem) { size_t i; BcBigDig carry = 0; assert(c->cap >= a->len); for (i = a->len - 1; i < a->len; --i) { BcBigDig in = ((BcBigDig) a->num[i]) + carry * BC_BASE_POW; assert(in / b < BC_BASE_POW); c->num[i] = (BcDig) (in / b); carry = in % b; } c->len = a->len; bc_num_clean(c); *rem = carry; assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); } static ssize_t bc_num_compare(const BcDig *restrict a, const BcDig *restrict b, size_t len) { size_t i; BcDig c = 0; for (i = len - 1; i < len && !(c = a[i] - b[i]); --i); return bc_num_neg(i + 1, c < 0); } ssize_t bc_num_cmp(const BcNum *a, const BcNum *b) { size_t i, min, a_int, b_int, diff, ardx, brdx; BcDig *max_num, *min_num; bool a_max, neg = false; ssize_t cmp; assert(a != NULL && b != NULL); if (a == b) return 0; if (BC_NUM_ZERO(a)) return bc_num_neg(b->len != 0, !BC_NUM_NEG(b)); if (BC_NUM_ZERO(b)) return bc_num_cmpZero(a); if (BC_NUM_NEG(a)) { if (BC_NUM_NEG(b)) neg = true; else return -1; } else if (BC_NUM_NEG(b)) return 1; a_int = bc_num_int(a); b_int = bc_num_int(b); a_int -= b_int; if (a_int) return neg ? -((ssize_t) a_int) : (ssize_t) a_int; ardx = BC_NUM_RDX_VAL(a); brdx = BC_NUM_RDX_VAL(b); a_max = (ardx > brdx); if (a_max) { min = brdx; diff = ardx - brdx; max_num = a->num + diff; min_num = b->num; } else { min = ardx; diff = brdx - ardx; max_num = b->num + diff; min_num = a->num; } cmp = bc_num_compare(max_num, min_num, b_int + min); if (cmp) return bc_num_neg((size_t) cmp, !a_max == !neg); for (max_num -= diff, i = diff - 1; i < diff; --i) { if (max_num[i]) return bc_num_neg(1, !a_max == !neg); } return 0; } void bc_num_truncate(BcNum *restrict n, size_t places) { size_t nrdx, places_rdx; if (!places) return; nrdx = BC_NUM_RDX_VAL(n); places_rdx = nrdx ? nrdx - BC_NUM_RDX(n->scale - places) : 0; assert(places <= n->scale && (BC_NUM_ZERO(n) || places_rdx <= n->len)); n->scale -= places; BC_NUM_RDX_SET(n, nrdx - places_rdx); if (BC_NUM_NONZERO(n)) { size_t pow; pow = n->scale % BC_BASE_DIGS; pow = pow ? BC_BASE_DIGS - pow : 0; pow = bc_num_pow10[pow]; n->len -= places_rdx; memmove(n->num, n->num + places_rdx, BC_NUM_SIZE(n->len)); // Clear the lower part of the last digit. if (BC_NUM_NONZERO(n)) n->num[0] -= n->num[0] % (BcDig) pow; bc_num_clean(n); } } void bc_num_extend(BcNum *restrict n, size_t places) { size_t nrdx, places_rdx; if (!places) return; if (BC_NUM_ZERO(n)) { n->scale += places; return; } nrdx = BC_NUM_RDX_VAL(n); places_rdx = BC_NUM_RDX(places + n->scale) - nrdx; if (places_rdx) { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); memset(n->num, 0, BC_NUM_SIZE(places_rdx)); } BC_NUM_RDX_SET(n, nrdx + places_rdx); n->scale += places; n->len += places_rdx; assert(BC_NUM_RDX_VAL(n) == BC_NUM_RDX(n->scale)); } static void bc_num_retireMul(BcNum *restrict n, size_t scale, bool neg1, bool neg2) { if (n->scale < scale) bc_num_extend(n, scale - n->scale); else bc_num_truncate(n, n->scale - scale); bc_num_clean(n); if (BC_NUM_NONZERO(n)) n->rdx = BC_NUM_NEG_VAL(n, !neg1 != !neg2); } static void bc_num_split(const BcNum *restrict n, size_t idx, BcNum *restrict a, BcNum *restrict b) { assert(BC_NUM_ZERO(a)); assert(BC_NUM_ZERO(b)); if (idx < n->len) { b->len = n->len - idx; a->len = idx; a->scale = b->scale = 0; BC_NUM_RDX_SET(a, 0); BC_NUM_RDX_SET(b, 0); assert(a->cap >= a->len); assert(b->cap >= b->len); memcpy(b->num, n->num + idx, BC_NUM_SIZE(b->len)); memcpy(a->num, n->num, BC_NUM_SIZE(idx)); bc_num_clean(b); } else bc_num_copy(a, n); bc_num_clean(a); } static size_t bc_num_shiftZero(BcNum *restrict n) { size_t i; assert(!BC_NUM_RDX_VAL(n) || BC_NUM_ZERO(n)); for (i = 0; i < n->len && !n->num[i]; ++i); n->len -= i; n->num += i; return i; } static void bc_num_unshiftZero(BcNum *restrict n, size_t places_rdx) { n->len += places_rdx; n->num -= places_rdx; } static void bc_num_shift(BcNum *restrict n, BcBigDig dig) { size_t i, len = n->len; BcBigDig carry = 0, pow; BcDig *ptr = n->num; assert(dig < BC_BASE_DIGS); pow = bc_num_pow10[dig]; dig = bc_num_pow10[BC_BASE_DIGS - dig]; for (i = len - 1; i < len; --i) { BcBigDig in, temp; in = ((BcBigDig) ptr[i]); temp = carry * dig; carry = in % pow; ptr[i] = ((BcDig) (in / pow)) + (BcDig) temp; } assert(!carry); } static void bc_num_shiftLeft(BcNum *restrict n, size_t places) { BcBigDig dig; size_t places_rdx; bool shift; if (!places) return; if (places > n->scale) { size_t size = bc_vm_growSize(BC_NUM_RDX(places - n->scale), n->len); if (size > SIZE_MAX - 1) bc_vm_err(BC_ERR_MATH_OVERFLOW); } if (BC_NUM_ZERO(n)) { if (n->scale >= places) n->scale -= places; else n->scale = 0; return; } dig = (BcBigDig) (places % BC_BASE_DIGS); shift = (dig != 0); places_rdx = BC_NUM_RDX(places); if (n->scale) { size_t nrdx = BC_NUM_RDX_VAL(n); if (nrdx >= places_rdx) { size_t mod = n->scale % BC_BASE_DIGS, revdig; mod = mod ? mod : BC_BASE_DIGS; revdig = dig ? BC_BASE_DIGS - dig : 0; if (mod + revdig > BC_BASE_DIGS) places_rdx = 1; else places_rdx = 0; } else places_rdx -= nrdx; } if (places_rdx) { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); memset(n->num, 0, BC_NUM_SIZE(places_rdx)); n->len += places_rdx; } if (places > n->scale) { n->scale = 0; BC_NUM_RDX_SET(n, 0); } else { n->scale -= places; BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale)); } if (shift) bc_num_shift(n, BC_BASE_DIGS - dig); bc_num_clean(n); } void bc_num_shiftRight(BcNum *restrict n, size_t places) { BcBigDig dig; size_t places_rdx, scale, scale_mod, int_len, expand; bool shift; if (!places) return; if (BC_NUM_ZERO(n)) { n->scale += places; bc_num_expand(n, BC_NUM_RDX(n->scale)); return; } dig = (BcBigDig) (places % BC_BASE_DIGS); shift = (dig != 0); scale = n->scale; scale_mod = scale % BC_BASE_DIGS; scale_mod = scale_mod ? scale_mod : BC_BASE_DIGS; int_len = bc_num_int(n); places_rdx = BC_NUM_RDX(places); if (scale_mod + dig > BC_BASE_DIGS) { expand = places_rdx - 1; places_rdx = 1; } else { expand = places_rdx; places_rdx = 0; } if (expand > int_len) expand -= int_len; else expand = 0; bc_num_extend(n, places_rdx * BC_BASE_DIGS); bc_num_expand(n, bc_vm_growSize(expand, n->len)); memset(n->num + n->len, 0, BC_NUM_SIZE(expand)); n->len += expand; n->scale = 0; BC_NUM_RDX_SET(n, 0); if (shift) bc_num_shift(n, dig); n->scale = scale + places; BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale)); bc_num_clean(n); assert(BC_NUM_RDX_VAL(n) <= n->len && n->len <= n->cap); assert(BC_NUM_RDX_VAL(n) == BC_NUM_RDX(n->scale)); } static void bc_num_inv(BcNum *a, BcNum *b, size_t scale) { BcNum one; BcDig num[2]; assert(BC_NUM_NONZERO(a)); bc_num_setup(&one, num, sizeof(num) / sizeof(BcDig)); bc_num_one(&one); bc_num_div(&one, a, b, scale); } #if BC_ENABLE_EXTRA_MATH static void bc_num_intop(const BcNum *a, const BcNum *b, BcNum *restrict c, BcBigDig *v) { if (BC_ERR(BC_NUM_RDX_VAL(b))) bc_vm_err(BC_ERR_MATH_NON_INTEGER); bc_num_copy(c, a); bc_num_bigdig(b, v); } #endif // BC_ENABLE_EXTRA_MATH static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) { BcDig *ptr_c, *ptr_l, *ptr_r; size_t i, min_rdx, max_rdx, diff, a_int, b_int, min_len, max_len, max_int; size_t len_l, len_r, ardx, brdx; bool b_neg, do_sub, do_rev_sub, carry, c_neg; // Because this function doesn't need to use scale (per the bc spec), // I am hijacking it to say whether it's doing an add or a subtract. // Convert substraction to addition of negative second operand. if (BC_NUM_ZERO(b)) { bc_num_copy(c, a); return; } if (BC_NUM_ZERO(a)) { bc_num_copy(c, b); c->rdx = BC_NUM_NEG_VAL(c, BC_NUM_NEG(b) != sub); return; } // Invert sign of b if it is to be subtracted. This operation must // preced the tests for any of the operands being zero. b_neg = (BC_NUM_NEG(b) != sub); // Actually add the numbers if their signs are equal, else subtract. do_sub = (BC_NUM_NEG(a) != b_neg); a_int = bc_num_int(a); b_int = bc_num_int(b); max_int = BC_MAX(a_int, b_int); ardx = BC_NUM_RDX_VAL(a); brdx = BC_NUM_RDX_VAL(b); min_rdx = BC_MIN(ardx, brdx); max_rdx = BC_MAX(ardx, brdx); diff = max_rdx - min_rdx; max_len = max_int + max_rdx; if (do_sub) { // Check whether b has to be subtracted from a or a from b. if (a_int != b_int) do_rev_sub = (a_int < b_int); else if (ardx > brdx) do_rev_sub = (bc_num_compare(a->num + diff, b->num, b->len) < 0); else do_rev_sub = (bc_num_compare(a->num, b->num + diff, a->len) <= 0); } else { // The result array of the addition might come out one element // longer than the bigger of the operand arrays. max_len += 1; do_rev_sub = (a_int < b_int); } assert(max_len <= c->cap); if (do_rev_sub) { ptr_l = b->num; ptr_r = a->num; len_l = b->len; len_r = a->len; } else { ptr_l = a->num; ptr_r = b->num; len_l = a->len; len_r = b->len; } ptr_c = c->num; carry = false; if (diff) { // If the rdx values of the operands do not match, the result will // have low end elements that are the positive or negative trailing // elements of the operand with higher rdx value. if ((ardx > brdx) != do_rev_sub) { // !do_rev_sub && ardx > brdx || do_rev_sub && brdx > ardx // The left operand has BcDig values that need to be copied, // either from a or from b (in case of a reversed subtraction). memcpy(ptr_c, ptr_l, BC_NUM_SIZE(diff)); ptr_l += diff; len_l -= diff; } else { // The right operand has BcDig values that need to be copied // or subtracted from zero (in case of a subtraction). if (do_sub) { // do_sub (do_rev_sub && ardx > brdx || // !do_rev_sub && brdx > ardx) for (i = 0; i < diff; i++) ptr_c[i] = bc_num_subDigits(0, ptr_r[i], &carry); } else { // !do_sub && brdx > ardx memcpy(ptr_c, ptr_r, BC_NUM_SIZE(diff)); } ptr_r += diff; len_r -= diff; } ptr_c += diff; } min_len = BC_MIN(len_l, len_r); // After dealing with possible low array elements that depend on only one // operand, the actual add or subtract can be performed as if the rdx of // both operands was the same. // Inlining takes care of eliminating constant zero arguments to // addDigit/subDigit (checked in disassembly of resulting bc binary // compiled with gcc and clang). if (do_sub) { for (i = 0; i < min_len; ++i) ptr_c[i] = bc_num_subDigits(ptr_l[i], ptr_r[i], &carry); for (; i < len_l; ++i) ptr_c[i] = bc_num_subDigits(ptr_l[i], 0, &carry); } else { for (i = 0; i < min_len; ++i) ptr_c[i] = bc_num_addDigits(ptr_l[i], ptr_r[i], &carry); for (; i < len_l; ++i) ptr_c[i] = bc_num_addDigits(ptr_l[i], 0, &carry); ptr_c[i] = bc_num_addDigits(0, 0, &carry); } assert(carry == false); // The result has the same sign as a, unless the operation was a // reverse subtraction (b - a). c_neg = BC_NUM_NEG(a) != (do_sub && do_rev_sub); BC_NUM_RDX_SET_NEG(c, max_rdx, c_neg); c->len = max_len; c->scale = BC_MAX(a->scale, b->scale); bc_num_clean(c); } static void bc_num_m_simp(const BcNum *a, const BcNum *b, BcNum *restrict c) { size_t i, alen = a->len, blen = b->len, clen; BcDig *ptr_a = a->num, *ptr_b = b->num, *ptr_c; BcBigDig sum = 0, carry = 0; assert(sizeof(sum) >= sizeof(BcDig) * 2); assert(!BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b)); clen = bc_vm_growSize(alen, blen); bc_num_expand(c, bc_vm_growSize(clen, 1)); ptr_c = c->num; memset(ptr_c, 0, BC_NUM_SIZE(c->cap)); for (i = 0; i < clen; ++i) { ssize_t sidx = (ssize_t) (i - blen + 1); size_t j = (size_t) BC_MAX(0, sidx), k = BC_MIN(i, blen - 1); for (; j < alen && k < blen; ++j, --k) { sum += ((BcBigDig) ptr_a[j]) * ((BcBigDig) ptr_b[k]); if (sum >= ((BcBigDig) BC_BASE_POW) * BC_BASE_POW) { carry += sum / BC_BASE_POW; sum %= BC_BASE_POW; } } if (sum >= BC_BASE_POW) { carry += sum / BC_BASE_POW; sum %= BC_BASE_POW; } ptr_c[i] = (BcDig) sum; assert(ptr_c[i] < BC_BASE_POW); sum = carry; carry = 0; } // This should always be true because there should be no carry on the last // digit; multiplication never goes above the sum of both lengths. assert(!sum); c->len = clen; } static void bc_num_shiftAddSub(BcNum *restrict n, const BcNum *restrict a, size_t shift, BcNumShiftAddOp op) { assert(n->len >= shift + a->len); assert(!BC_NUM_RDX_VAL(n) && !BC_NUM_RDX_VAL(a)); op(n->num + shift, a->num, a->len); } static void bc_num_k(BcNum *a, BcNum *b, BcNum *restrict c) { size_t max, max2, total; BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp; BcDig *digs, *dig_ptr; BcNumShiftAddOp op; bool aone = BC_NUM_ONE(a); assert(BC_NUM_ZERO(c)); if (BC_NUM_ZERO(a) || BC_NUM_ZERO(b)) return; if (aone || BC_NUM_ONE(b)) { bc_num_copy(c, aone ? b : a); if ((aone && BC_NUM_NEG(a)) || BC_NUM_NEG(b)) BC_NUM_NEG_TGL(c); return; } if (a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN) { bc_num_m_simp(a, b, c); return; } max = BC_MAX(a->len, b->len); max = BC_MAX(max, BC_NUM_DEF_SIZE); max2 = (max + 1) / 2; total = bc_vm_arraySize(BC_NUM_KARATSUBA_ALLOCS, max); BC_SIG_LOCK; digs = dig_ptr = bc_vm_malloc(BC_NUM_SIZE(total)); bc_num_setup(&l1, dig_ptr, max); dig_ptr += max; bc_num_setup(&h1, dig_ptr, max); dig_ptr += max; bc_num_setup(&l2, dig_ptr, max); dig_ptr += max; bc_num_setup(&h2, dig_ptr, max); dig_ptr += max; bc_num_setup(&m1, dig_ptr, max); dig_ptr += max; bc_num_setup(&m2, dig_ptr, max); max = bc_vm_growSize(max, 1); bc_num_init(&z0, max); bc_num_init(&z1, max); bc_num_init(&z2, max); max = bc_vm_growSize(max, max) + 1; bc_num_init(&temp, max); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_split(a, max2, &l1, &h1); bc_num_split(b, max2, &l2, &h2); bc_num_expand(c, max); c->len = max; memset(c->num, 0, BC_NUM_SIZE(c->len)); bc_num_sub(&h1, &l1, &m1, 0); bc_num_sub(&l2, &h2, &m2, 0); if (BC_NUM_NONZERO(&h1) && BC_NUM_NONZERO(&h2)) { assert(BC_NUM_RDX_VALID_NP(h1)); assert(BC_NUM_RDX_VALID_NP(h2)); bc_num_m(&h1, &h2, &z2, 0); bc_num_clean(&z2); bc_num_shiftAddSub(c, &z2, max2 * 2, bc_num_addArrays); bc_num_shiftAddSub(c, &z2, max2, bc_num_addArrays); } if (BC_NUM_NONZERO(&l1) && BC_NUM_NONZERO(&l2)) { assert(BC_NUM_RDX_VALID_NP(l1)); assert(BC_NUM_RDX_VALID_NP(l2)); bc_num_m(&l1, &l2, &z0, 0); bc_num_clean(&z0); bc_num_shiftAddSub(c, &z0, max2, bc_num_addArrays); bc_num_shiftAddSub(c, &z0, 0, bc_num_addArrays); } if (BC_NUM_NONZERO(&m1) && BC_NUM_NONZERO(&m2)) { assert(BC_NUM_RDX_VALID_NP(m1)); assert(BC_NUM_RDX_VALID_NP(m1)); bc_num_m(&m1, &m2, &z1, 0); bc_num_clean(&z1); op = (BC_NUM_NEG_NP(m1) != BC_NUM_NEG_NP(m2)) ? bc_num_subArrays : bc_num_addArrays; bc_num_shiftAddSub(c, &z1, max2, op); } err: BC_SIG_MAYLOCK; free(digs); bc_num_free(&temp); bc_num_free(&z2); bc_num_free(&z1); bc_num_free(&z0); BC_LONGJMP_CONT; } static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcNum cpa, cpb; size_t ascale, bscale, ardx, brdx, azero = 0, bzero = 0, zero, len, rscale; assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_zero(c); ascale = a->scale; bscale = b->scale; scale = BC_MAX(scale, ascale); scale = BC_MAX(scale, bscale); rscale = ascale + bscale; scale = BC_MIN(rscale, scale); if ((a->len == 1 || b->len == 1) && !a->rdx && !b->rdx) { BcNum *operand; BcBigDig dig; if (a->len == 1) { dig = (BcBigDig) a->num[0]; operand = b; } else { dig = (BcBigDig) b->num[0]; operand = a; } bc_num_mulArray(operand, dig, c); if (BC_NUM_NONZERO(c)) c->rdx = BC_NUM_NEG_VAL(c, BC_NUM_NEG(a) != BC_NUM_NEG(b)); return; } assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); BC_SIG_LOCK; bc_num_init(&cpa, a->len + BC_NUM_RDX_VAL(a)); bc_num_init(&cpb, b->len + BC_NUM_RDX_VAL(b)); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_copy(&cpa, a); bc_num_copy(&cpb, b); assert(BC_NUM_RDX_VALID_NP(cpa)); assert(BC_NUM_RDX_VALID_NP(cpb)); BC_NUM_NEG_CLR_NP(cpa); BC_NUM_NEG_CLR_NP(cpb); assert(BC_NUM_RDX_VALID_NP(cpa)); assert(BC_NUM_RDX_VALID_NP(cpb)); ardx = BC_NUM_RDX_VAL_NP(cpa) * BC_BASE_DIGS; bc_num_shiftLeft(&cpa, ardx); brdx = BC_NUM_RDX_VAL_NP(cpb) * BC_BASE_DIGS; bc_num_shiftLeft(&cpb, brdx); // We need to reset the jump here because azero and bzero are used in the // cleanup, and local variables are not guaranteed to be the same after a // jump. BC_SIG_LOCK; BC_UNSETJMP; azero = bc_num_shiftZero(&cpa); bzero = bc_num_shiftZero(&cpb); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_clean(&cpa); bc_num_clean(&cpb); bc_num_k(&cpa, &cpb, c); zero = bc_vm_growSize(azero, bzero); len = bc_vm_growSize(c->len, zero); bc_num_expand(c, len); bc_num_shiftLeft(c, (len - c->len) * BC_BASE_DIGS); bc_num_shiftRight(c, ardx + brdx); bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b)); err: BC_SIG_MAYLOCK; bc_num_unshiftZero(&cpb, bzero); bc_num_free(&cpb); bc_num_unshiftZero(&cpa, azero); bc_num_free(&cpa); BC_LONGJMP_CONT; } static bool bc_num_nonZeroDig(BcDig *restrict a, size_t len) { size_t i; bool nonzero = false; for (i = len - 1; !nonzero && i < len; --i) nonzero = (a[i] != 0); return nonzero; } static ssize_t bc_num_divCmp(const BcDig *a, const BcNum *b, size_t len) { ssize_t cmp; if (b->len > len && a[len]) cmp = bc_num_compare(a, b->num, len + 1); else if (b->len <= len) { if (a[len]) cmp = 1; else cmp = bc_num_compare(a, b->num, len); } else cmp = -1; return cmp; } static void bc_num_divExtend(BcNum *restrict a, BcNum *restrict b, BcBigDig divisor) { size_t pow; assert(divisor < BC_BASE_POW); pow = BC_BASE_DIGS - bc_num_log10((size_t) divisor); bc_num_shiftLeft(a, pow); bc_num_shiftLeft(b, pow); } static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, BcNum *restrict c, size_t scale) { BcBigDig divisor; size_t len, end, i, rdx; BcNum cpb; bool nonzero = false; assert(b->len < a->len); len = b->len; end = a->len - len; assert(len >= 1); bc_num_expand(c, a->len); memset(c->num, 0, c->cap * sizeof(BcDig)); BC_NUM_RDX_SET(c, BC_NUM_RDX_VAL(a)); c->scale = a->scale; c->len = a->len; divisor = (BcBigDig) b->num[len - 1]; if (len > 1 && bc_num_nonZeroDig(b->num, len - 1)) { nonzero = (divisor > 1 << ((10 * BC_BASE_DIGS) / 6 + 1)); if (!nonzero) { bc_num_divExtend(a, b, divisor); len = BC_MAX(a->len, b->len); bc_num_expand(a, len + 1); if (len + 1 > a->len) a->len = len + 1; len = b->len; end = a->len - len; divisor = (BcBigDig) b->num[len - 1]; nonzero = bc_num_nonZeroDig(b->num, len - 1); } } divisor += nonzero; bc_num_expand(c, a->len); memset(c->num, 0, BC_NUM_SIZE(c->cap)); assert(c->scale >= scale); rdx = BC_NUM_RDX_VAL(c) - BC_NUM_RDX(scale); BC_SIG_LOCK; bc_num_init(&cpb, len + 1); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; i = end - 1; for (; i < end && i >= rdx && BC_NUM_NONZERO(a); --i) { ssize_t cmp; BcDig *n; BcBigDig result; n = a->num + i; assert(n >= a->num); result = 0; cmp = bc_num_divCmp(n, b, len); while (cmp >= 0) { BcBigDig n1, dividend, q; n1 = (BcBigDig) n[len]; dividend = n1 * BC_BASE_POW + (BcBigDig) n[len - 1]; q = (dividend / divisor); if (q <= 1) { q = 1; bc_num_subArrays(n, b->num, len); } else { assert(q <= BC_BASE_POW); bc_num_mulArray(b, (BcBigDig) q, &cpb); bc_num_subArrays(n, cpb.num, cpb.len); } result += q; assert(result <= BC_BASE_POW); if (nonzero) cmp = bc_num_divCmp(n, b, len); else cmp = -1; } assert(result < BC_BASE_POW); c->num[i] = (BcDig) result; } err: BC_SIG_MAYLOCK; bc_num_free(&cpb); BC_LONGJMP_CONT; } static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { size_t len, cpardx; BcNum cpa, cpb; if (BC_NUM_ZERO(b)) bc_vm_err(BC_ERR_MATH_DIVIDE_BY_ZERO); if (BC_NUM_ZERO(a)) { bc_num_setToZero(c, scale); return; } if (BC_NUM_ONE(b)) { bc_num_copy(c, a); bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b)); return; } if (!BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b) && b->len == 1 && !scale) { BcBigDig rem; bc_num_divArray(a, (BcBigDig) b->num[0], c, &rem); bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b)); return; } len = bc_num_divReq(a, b, scale); BC_SIG_LOCK; bc_num_init(&cpa, len); bc_num_copy(&cpa, a); bc_num_createCopy(&cpb, b); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; len = b->len; if (len > cpa.len) { bc_num_expand(&cpa, bc_vm_growSize(len, 2)); bc_num_extend(&cpa, (len - cpa.len) * BC_BASE_DIGS); } cpardx = BC_NUM_RDX_VAL_NP(cpa); cpa.scale = cpardx * BC_BASE_DIGS; bc_num_extend(&cpa, b->scale); cpardx = BC_NUM_RDX_VAL_NP(cpa) - BC_NUM_RDX(b->scale); BC_NUM_RDX_SET_NP(cpa, cpardx); cpa.scale = cpardx * BC_BASE_DIGS; if (scale > cpa.scale) { bc_num_extend(&cpa, scale); cpardx = BC_NUM_RDX_VAL_NP(cpa); cpa.scale = cpardx * BC_BASE_DIGS; } if (cpa.cap == cpa.len) bc_num_expand(&cpa, bc_vm_growSize(cpa.len, 1)); // We want an extra zero in front to make things simpler. cpa.num[cpa.len++] = 0; if (cpardx == cpa.len) cpa.len = bc_num_nonzeroLen(&cpa); if (BC_NUM_RDX_VAL_NP(cpb) == cpb.len) cpb.len = bc_num_nonzeroLen(&cpb); cpb.scale = 0; BC_NUM_RDX_SET_NP(cpb, 0); bc_num_d_long(&cpa, &cpb, c, scale); bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b)); err: BC_SIG_MAYLOCK; bc_num_free(&cpb); bc_num_free(&cpa); BC_LONGJMP_CONT; } static void bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c, BcNum *restrict d, size_t scale, size_t ts) { BcNum temp; bool neg; if (BC_NUM_ZERO(b)) bc_vm_err(BC_ERR_MATH_DIVIDE_BY_ZERO); if (BC_NUM_ZERO(a)) { bc_num_setToZero(c, ts); bc_num_setToZero(d, ts); return; } BC_SIG_LOCK; bc_num_init(&temp, d->cap); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_d(a, b, c, scale); if (scale) scale = ts + 1; assert(BC_NUM_RDX_VALID(c)); assert(BC_NUM_RDX_VALID(b)); bc_num_m(c, b, &temp, scale); bc_num_sub(a, &temp, d, scale); if (ts > d->scale && BC_NUM_NONZERO(d)) bc_num_extend(d, ts - d->scale); neg = BC_NUM_NEG(d); bc_num_retireMul(d, ts, BC_NUM_NEG(a), BC_NUM_NEG(b)); d->rdx = BC_NUM_NEG_VAL(d, BC_NUM_NONZERO(d) ? neg : false); err: BC_SIG_MAYLOCK; bc_num_free(&temp); BC_LONGJMP_CONT; } static void bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcNum c1; size_t ts; ts = bc_vm_growSize(scale, b->scale); ts = BC_MAX(ts, a->scale); BC_SIG_LOCK; bc_num_init(&c1, bc_num_mulReq(a, b, ts)); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_r(a, b, &c1, c, scale, ts); err: BC_SIG_MAYLOCK; bc_num_free(&c1); BC_LONGJMP_CONT; } static void bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcNum copy; BcBigDig pow = 0; size_t i, powrdx, resrdx; bool neg, zero; if (BC_ERR(BC_NUM_RDX_VAL(b))) bc_vm_err(BC_ERR_MATH_NON_INTEGER); if (BC_NUM_ZERO(b)) { bc_num_one(c); return; } if (BC_NUM_ZERO(a)) { if (BC_NUM_NEG(b)) bc_vm_err(BC_ERR_MATH_DIVIDE_BY_ZERO); bc_num_setToZero(c, scale); return; } if (BC_NUM_ONE(b)) { if (!BC_NUM_NEG(b)) bc_num_copy(c, a); else bc_num_inv(a, c, scale); return; } BC_SIG_LOCK; neg = BC_NUM_NEG(b); BC_NUM_NEG_CLR(b); bc_num_bigdig(b, &pow); b->rdx = BC_NUM_NEG_VAL(b, neg); bc_num_createCopy(©, a); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; if (!neg) { size_t max = BC_MAX(scale, a->scale), scalepow = a->scale * pow; scale = BC_MIN(scalepow, max); } for (powrdx = a->scale; !(pow & 1); pow >>= 1) { powrdx <<= 1; assert(BC_NUM_RDX_VALID_NP(copy)); bc_num_mul(©, ©, ©, powrdx); } bc_num_copy(c, ©); resrdx = powrdx; while (pow >>= 1) { powrdx <<= 1; assert(BC_NUM_RDX_VALID_NP(copy)); bc_num_mul(©, ©, ©, powrdx); if (pow & 1) { resrdx += powrdx; assert(BC_NUM_RDX_VALID(c)); assert(BC_NUM_RDX_VALID_NP(copy)); bc_num_mul(c, ©, c, resrdx); } } if (neg) bc_num_inv(c, c, scale); if (c->scale > scale) bc_num_truncate(c, c->scale - scale); // We can't use bc_num_clean() here. for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i]; if (zero) bc_num_setToZero(c, scale); err: BC_SIG_MAYLOCK; bc_num_free(©); BC_LONGJMP_CONT; } #if BC_ENABLE_EXTRA_MATH static void bc_num_place(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcBigDig val = 0; BC_UNUSED(scale); bc_num_intop(a, b, c, &val); if (val < c->scale) bc_num_truncate(c, c->scale - val); else if (val > c->scale) bc_num_extend(c, val - c->scale); } static void bc_num_left(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcBigDig val = 0; BC_UNUSED(scale); bc_num_intop(a, b, c, &val); bc_num_shiftLeft(c, (size_t) val); } static void bc_num_right(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcBigDig val = 0; BC_UNUSED(scale); bc_num_intop(a, b, c, &val); if (BC_NUM_ZERO(c)) return; bc_num_shiftRight(c, (size_t) val); } #endif // BC_ENABLE_EXTRA_MATH static void bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale, BcNumBinaryOp op, size_t req) { BcNum *ptr_a, *ptr_b, num2; bool init = false; assert(a != NULL && b != NULL && c != NULL && op != NULL); assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); BC_SIG_LOCK; if (c == a) { ptr_a = &num2; memcpy(ptr_a, c, sizeof(BcNum)); init = true; } else { ptr_a = a; } if (c == b) { ptr_b = &num2; if (c != a) { memcpy(ptr_b, c, sizeof(BcNum)); init = true; } } else { ptr_b = b; } if (init) { bc_num_init(c, req); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; } else { BC_SIG_UNLOCK; bc_num_expand(c, req); } op(ptr_a, ptr_b, c, scale); assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(BC_NUM_RDX_VALID(c)); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); err: if (init) { BC_SIG_MAYLOCK; bc_num_free(&num2); BC_LONGJMP_CONT; } } #if !defined(NDEBUG) || BC_ENABLE_LIBRARY bool bc_num_strValid(const char *restrict val) { bool radix = false; size_t i, len = strlen(val); if (!len) return true; for (i = 0; i < len; ++i) { BcDig c = val[i]; if (c == '.') { if (radix) return false; radix = true; continue; } if (!(isdigit(c) || isupper(c))) return false; } return true; } #endif // !defined(NDEBUG) || BC_ENABLE_LIBRARY static BcBigDig bc_num_parseChar(char c, size_t base_t) { if (isupper(c)) { c = BC_NUM_NUM_LETTER(c); c = ((size_t) c) >= base_t ? (char) base_t - 1 : c; } else c -= '0'; return (BcBigDig) (uchar) c; } static void bc_num_parseDecimal(BcNum *restrict n, const char *restrict val) { size_t len, i, temp, mod; const char *ptr; bool zero = true, rdx; for (i = 0; val[i] == '0'; ++i); val += i; assert(!val[0] || isalnum(val[0]) || val[0] == '.'); // All 0's. We can just return, since this // procedure expects a virgin (already 0) BcNum. if (!val[0]) return; len = strlen(val); ptr = strchr(val, '.'); rdx = (ptr != NULL); for (i = 0; i < len && (zero = (val[i] == '0' || val[i] == '.')); ++i); n->scale = (size_t) (rdx * (((uintptr_t) (val + len)) - (((uintptr_t) ptr) + 1))); BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale)); i = len - (ptr == val ? 0 : i) - rdx; temp = BC_NUM_ROUND_POW(i); mod = n->scale % BC_BASE_DIGS; i = mod ? BC_BASE_DIGS - mod : 0; n->len = ((temp + i) / BC_BASE_DIGS); bc_num_expand(n, n->len); memset(n->num, 0, BC_NUM_SIZE(n->len)); if (zero) { // I think I can set rdx directly to zero here because n should be a // new number with sign set to false. n->len = n->rdx = 0; } else { BcBigDig exp, pow; assert(i <= BC_NUM_BIGDIG_MAX); exp = (BcBigDig) i; pow = bc_num_pow10[exp]; for (i = len - 1; i < len; --i, ++exp) { char c = val[i]; if (c == '.') exp -= 1; else { size_t idx = exp / BC_BASE_DIGS; if (isupper(c)) c = '9'; n->num[idx] += (((BcBigDig) c) - '0') * pow; if ((exp + 1) % BC_BASE_DIGS == 0) pow = 1; else pow *= BC_BASE; } } } } static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, BcBigDig base) { BcNum temp, mult1, mult2, result1, result2, *m1, *m2, *ptr; char c = 0; bool zero = true; BcBigDig v; size_t i, digs, len = strlen(val); for (i = 0; zero && i < len; ++i) zero = (val[i] == '.' || val[i] == '0'); if (zero) return; BC_SIG_LOCK; bc_num_init(&temp, BC_NUM_BIGDIG_LOG10); bc_num_init(&mult1, BC_NUM_BIGDIG_LOG10); BC_SETJMP_LOCKED(int_err); BC_SIG_UNLOCK; for (i = 0; i < len && (c = val[i]) && c != '.'; ++i) { v = bc_num_parseChar(c, base); bc_num_mulArray(n, base, &mult1); bc_num_bigdig2num(&temp, v); bc_num_add(&mult1, &temp, n, 0); } if (i == len && !val[i]) goto int_err; assert(val[i] == '.'); BC_SIG_LOCK; BC_UNSETJMP; bc_num_init(&mult2, BC_NUM_BIGDIG_LOG10); bc_num_init(&result1, BC_NUM_DEF_SIZE); bc_num_init(&result2, BC_NUM_DEF_SIZE); bc_num_one(&mult1); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; m1 = &mult1; m2 = &mult2; for (i += 1, digs = 0; i < len && (c = val[i]); ++i, ++digs) { size_t rdx; v = bc_num_parseChar(c, base); bc_num_mulArray(&result1, base, &result2); bc_num_bigdig2num(&temp, v); bc_num_add(&result2, &temp, &result1, 0); bc_num_mulArray(m1, base, m2); rdx = BC_NUM_RDX_VAL(m2); if (m2->len < rdx) m2->len = rdx; ptr = m1; m1 = m2; m2 = ptr; } // This one cannot be a divide by 0 because mult starts out at 1, then is // multiplied by base, and base cannot be 0, so mult cannot be 0. bc_num_div(&result1, m1, &result2, digs * 2); bc_num_truncate(&result2, digs); bc_num_add(n, &result2, n, digs); if (BC_NUM_NONZERO(n)) { if (n->scale < digs) bc_num_extend(n, digs - n->scale); } else bc_num_zero(n); err: BC_SIG_MAYLOCK; bc_num_free(&result2); bc_num_free(&result1); bc_num_free(&mult2); int_err: BC_SIG_MAYLOCK; bc_num_free(&mult1); bc_num_free(&temp); BC_LONGJMP_CONT; } static inline void bc_num_printNewline(void) { #if !BC_ENABLE_LIBRARY if (vm.nchars >= vm.line_len - 1) { bc_vm_putchar('\\'); bc_vm_putchar('\n'); } #endif // !BC_ENABLE_LIBRARY } static void bc_num_putchar(int c) { if (c != '\n') bc_num_printNewline(); bc_vm_putchar(c); } #if DC_ENABLED && !BC_ENABLE_LIBRARY static void bc_num_printChar(size_t n, size_t len, bool rdx) { BC_UNUSED(rdx); BC_UNUSED(len); assert(len == 1); bc_vm_putchar((uchar) n); } #endif // DC_ENABLED && !BC_ENABLE_LIBRARY static void bc_num_printDigits(size_t n, size_t len, bool rdx) { size_t exp, pow; bc_num_putchar(rdx ? '.' : ' '); for (exp = 0, pow = 1; exp < len - 1; ++exp, pow *= BC_BASE); for (exp = 0; exp < len; pow /= BC_BASE, ++exp) { size_t dig = n / pow; n -= dig * pow; bc_num_putchar(((uchar) dig) + '0'); } } static void bc_num_printHex(size_t n, size_t len, bool rdx) { BC_UNUSED(len); assert(len == 1); if (rdx) bc_num_putchar('.'); bc_num_putchar(bc_num_hex_digits[n]); } static void bc_num_printDecimal(const BcNum *restrict n) { size_t i, j, rdx = BC_NUM_RDX_VAL(n); bool zero = true; size_t buffer[BC_BASE_DIGS]; if (BC_NUM_NEG(n)) bc_num_putchar('-'); for (i = n->len - 1; i < n->len; --i) { BcDig n9 = n->num[i]; size_t temp; bool irdx = (i == rdx - 1); zero = (zero & !irdx); temp = n->scale % BC_BASE_DIGS; temp = i || !temp ? 0 : BC_BASE_DIGS - temp; memset(buffer, 0, BC_BASE_DIGS * sizeof(size_t)); for (j = 0; n9 && j < BC_BASE_DIGS; ++j) { buffer[j] = ((size_t) n9) % BC_BASE; n9 /= BC_BASE; } for (j = BC_BASE_DIGS - 1; j < BC_BASE_DIGS && j >= temp; --j) { bool print_rdx = (irdx & (j == BC_BASE_DIGS - 1)); zero = (zero && buffer[j] == 0); if (!zero) bc_num_printHex(buffer[j], 1, print_rdx); } } } #if BC_ENABLE_EXTRA_MATH static void bc_num_printExponent(const BcNum *restrict n, bool eng) { size_t places, mod, nrdx = BC_NUM_RDX_VAL(n); bool neg = (n->len <= nrdx); BcNum temp, exp; BcDig digs[BC_NUM_BIGDIG_LOG10]; BC_SIG_LOCK; bc_num_createCopy(&temp, n); BC_SETJMP_LOCKED(exit); BC_SIG_UNLOCK; if (neg) { size_t i, idx = bc_num_nonzeroLen(n) - 1; places = 1; for (i = BC_BASE_DIGS - 1; i < BC_BASE_DIGS; --i) { if (bc_num_pow10[i] > (BcBigDig) n->num[idx]) places += 1; else break; } places += (nrdx - (idx + 1)) * BC_BASE_DIGS; mod = places % 3; if (eng && mod != 0) places += 3 - mod; bc_num_shiftLeft(&temp, places); } else { places = bc_num_intDigits(n) - 1; mod = places % 3; if (eng && mod != 0) places -= 3 - (3 - mod); bc_num_shiftRight(&temp, places); } bc_num_printDecimal(&temp); bc_num_putchar('e'); if (!places) { bc_num_printHex(0, 1, false); goto exit; } if (neg) bc_num_putchar('-'); bc_num_setup(&exp, digs, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(&exp, (BcBigDig) places); bc_num_printDecimal(&exp); exit: BC_SIG_MAYLOCK; bc_num_free(&temp); BC_LONGJMP_CONT; } #endif // BC_ENABLE_EXTRA_MATH static void bc_num_printFixup(BcNum *restrict n, BcBigDig rem, BcBigDig pow, size_t idx) { size_t i, len = n->len - idx; BcBigDig acc; BcDig *a = n->num + idx; if (len < 2) return; for (i = len - 1; i > 0; --i) { acc = ((BcBigDig) a[i]) * rem + ((BcBigDig) a[i - 1]); a[i - 1] = (BcDig) (acc % pow); acc /= pow; acc += (BcBigDig) a[i]; if (acc >= BC_BASE_POW) { if (i == len - 1) { len = bc_vm_growSize(len, 1); bc_num_expand(n, bc_vm_growSize(len, idx)); a = n->num + idx; a[len - 1] = 0; } a[i + 1] += acc / BC_BASE_POW; acc %= BC_BASE_POW; } assert(acc < BC_BASE_POW); a[i] = (BcDig) acc; } n->len = len + idx; } static void bc_num_printPrepare(BcNum *restrict n, BcBigDig rem, BcBigDig pow) { size_t i; for (i = 0; i < n->len; ++i) bc_num_printFixup(n, rem, pow, i); for (i = 0; i < n->len; ++i) { assert(pow == ((BcBigDig) ((BcDig) pow))); if (n->num[i] >= (BcDig) pow) { if (i + 1 == n->len) { n->len = bc_vm_growSize(n->len, 1); bc_num_expand(n, n->len); n->num[i + 1] = 0; } assert(pow < BC_BASE_POW); n->num[i + 1] += n->num[i] / ((BcDig) pow); n->num[i] %= (BcDig) pow; } } } static void bc_num_printNum(BcNum *restrict n, BcBigDig base, size_t len, BcNumDigitOp print) { BcVec stack; BcNum intp, fracp1, fracp2, digit, flen1, flen2, *n1, *n2, *temp; BcBigDig dig = 0, *ptr, acc, exp; size_t i, j, nrdx; bool radix; BcDig digit_digs[BC_NUM_BIGDIG_LOG10 + 1]; assert(base > 1); if (BC_NUM_ZERO(n)) { print(0, len, false); return; } // This function uses an algorithm that Stefan Esser came // up with to print the integer part of a number. What it does is convert // intp into a number of the specified base, but it does it directly, // instead of just doing a series of divisions and printing the remainders // in reverse order. // // Let me explain in a bit more detail: // // The algorithm takes the current least significant digit (after intp has // been converted to an integer) and the next to least significant digit, // and it converts the least significant digit into one of the specified // base, putting any overflow into the next to least significant digit. It // iterates through the whole number, from least significant to most // significant, doing this conversion. At the end of that iteration, the // least significant digit is converted, but the others are not, so it // iterates again, starting at the next to least significant digit. It keeps // doing that conversion, skipping one more digit than the last time, until // all digits have been converted. Then it prints them in reverse order. // // That is the gist of the algorithm. It leaves out several things, such as // the fact that digits are not always converted into the specified base, // but into something close, basically a power of the specified base. In // Stefan's words, "You could consider BcDigs to be of base 10^BC_BASE_DIGS // in the normal case and obase^N for the largest value of N that satisfies // obase^N <= 10^BC_BASE_DIGS. [This means that] the result is not in base // "obase", but in base "obase^N", which happens to be printable as a number // of base "obase" without consideration for neighbouring BcDigs." This fact // is what necessitates the existence of the loop later in this function. // // The conversion happens in bc_num_printPrepare() where the outer loop // happens and bc_num_printFixup() where the inner loop, or actual // conversion, happens. nrdx = BC_NUM_RDX_VAL(n); BC_SIG_LOCK; bc_vec_init(&stack, sizeof(BcBigDig), NULL); bc_num_init(&fracp1, nrdx); bc_num_createCopy(&intp, n); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_truncate(&intp, intp.scale); bc_num_sub(n, &intp, &fracp1, 0); if (base != vm.last_base) { vm.last_pow = 1; vm.last_exp = 0; while (vm.last_pow * base <= BC_BASE_POW) { vm.last_pow *= base; vm.last_exp += 1; } vm.last_rem = BC_BASE_POW - vm.last_pow; vm.last_base = base; } exp = vm.last_exp; if (vm.last_rem != 0) bc_num_printPrepare(&intp, vm.last_rem, vm.last_pow); for (i = 0; i < intp.len; ++i) { acc = (BcBigDig) intp.num[i]; for (j = 0; j < exp && (i < intp.len - 1 || acc != 0); ++j) { if (j != exp - 1) { dig = acc % base; acc /= base; } else { dig = acc; acc = 0; } assert(dig < base); bc_vec_push(&stack, &dig); } assert(acc == 0); } for (i = 0; i < stack.len; ++i) { ptr = bc_vec_item_rev(&stack, i); assert(ptr != NULL); print(*ptr, len, false); } if (!n->scale) goto err; BC_SIG_LOCK; BC_UNSETJMP; bc_num_init(&fracp2, nrdx); bc_num_setup(&digit, digit_digs, sizeof(digit_digs) / sizeof(BcDig)); bc_num_init(&flen1, BC_NUM_BIGDIG_LOG10); bc_num_init(&flen2, BC_NUM_BIGDIG_LOG10); BC_SETJMP_LOCKED(frac_err); BC_SIG_UNLOCK; bc_num_one(&flen1); radix = true; n1 = &flen1; n2 = &flen2; fracp2.scale = n->scale; BC_NUM_RDX_SET_NP(fracp2, BC_NUM_RDX(fracp2.scale)); while (bc_num_intDigits(n1) < n->scale + 1) { bc_num_expand(&fracp2, fracp1.len + 1); bc_num_mulArray(&fracp1, base, &fracp2); nrdx = BC_NUM_RDX_VAL_NP(fracp2); if (fracp2.len < nrdx) fracp2.len = nrdx; // fracp is guaranteed to be non-negative and small enough. bc_num_bigdig2(&fracp2, &dig); bc_num_bigdig2num(&digit, dig); bc_num_sub(&fracp2, &digit, &fracp1, 0); print(dig, len, radix); bc_num_mulArray(n1, base, n2); radix = false; temp = n1; n1 = n2; n2 = temp; } frac_err: BC_SIG_MAYLOCK; bc_num_free(&flen2); bc_num_free(&flen1); bc_num_free(&fracp2); err: BC_SIG_MAYLOCK; bc_num_free(&fracp1); bc_num_free(&intp); bc_vec_free(&stack); BC_LONGJMP_CONT; } static void bc_num_printBase(BcNum *restrict n, BcBigDig base) { size_t width; BcNumDigitOp print; bool neg = BC_NUM_NEG(n); if (neg) bc_num_putchar('-'); BC_NUM_NEG_CLR(n); if (base <= BC_NUM_MAX_POSIX_IBASE) { width = 1; print = bc_num_printHex; } else { assert(base <= BC_BASE_POW); width = bc_num_log10(base - 1); print = bc_num_printDigits; } bc_num_printNum(n, base, width, print); n->rdx = BC_NUM_NEG_VAL(n, neg); } #if DC_ENABLED && !BC_ENABLE_LIBRARY void bc_num_stream(BcNum *restrict n, BcBigDig base) { bc_num_printNum(n, base, 1, bc_num_printChar); } #endif // DC_ENABLED && !BC_ENABLE_LIBRARY void bc_num_setup(BcNum *restrict n, BcDig *restrict num, size_t cap) { assert(n != NULL); n->num = num; n->cap = cap; bc_num_zero(n); } void bc_num_init(BcNum *restrict n, size_t req) { BcDig *num; BC_SIG_ASSERT_LOCKED; assert(n != NULL); req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE; if (req == BC_NUM_DEF_SIZE && vm.temps.len) { BcNum *nptr = bc_vec_top(&vm.temps); num = nptr->num; bc_vec_pop(&vm.temps); } else num = bc_vm_malloc(BC_NUM_SIZE(req)); bc_num_setup(n, num, req); } void bc_num_clear(BcNum *restrict n) { n->num = NULL; n->cap = 0; } void bc_num_free(void *num) { BcNum *n = (BcNum*) num; BC_SIG_ASSERT_LOCKED; assert(n != NULL); if (n->cap == BC_NUM_DEF_SIZE) bc_vec_push(&vm.temps, n); else free(n->num); } void bc_num_copy(BcNum *d, const BcNum *s) { assert(d != NULL && s != NULL); if (d == s) return; bc_num_expand(d, s->len); d->len = s->len; // I can just copy directly here. d->rdx = s->rdx; d->scale = s->scale; memcpy(d->num, s->num, BC_NUM_SIZE(d->len)); } void bc_num_createCopy(BcNum *d, const BcNum *s) { BC_SIG_ASSERT_LOCKED; bc_num_init(d, s->len); bc_num_copy(d, s); } void bc_num_createFromBigdig(BcNum *n, BcBigDig val) { BC_SIG_ASSERT_LOCKED; bc_num_init(n, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(n, val); } size_t bc_num_scale(const BcNum *restrict n) { return n->scale; } size_t bc_num_len(const BcNum *restrict n) { size_t len = n->len; - if (BC_NUM_ZERO(n)) return 0; + if (BC_NUM_ZERO(n)) return n->scale ? n->scale : 1; if (BC_NUM_RDX_VAL(n) == len) { size_t zero, scale; len = bc_num_nonzeroLen(n); scale = n->scale % BC_BASE_DIGS; scale = scale ? scale : BC_BASE_DIGS; zero = bc_num_zeroDigits(n->num + len - 1); len = len * BC_BASE_DIGS - zero - (BC_BASE_DIGS - scale); } else len = bc_num_intDigits(n) + n->scale; return len; } void bc_num_parse(BcNum *restrict n, const char *restrict val, BcBigDig base) { assert(n != NULL && val != NULL && base); assert(base >= BC_NUM_MIN_BASE && base <= vm.maxes[BC_PROG_GLOBALS_IBASE]); assert(bc_num_strValid(val)); if (!val[1]) { BcBigDig dig = bc_num_parseChar(val[0], BC_NUM_MAX_LBASE); bc_num_bigdig2num(n, dig); } else if (base == BC_BASE) bc_num_parseDecimal(n, val); else bc_num_parseBase(n, val, base); assert(BC_NUM_RDX_VALID(n)); } void bc_num_print(BcNum *restrict n, BcBigDig base, bool newline) { assert(n != NULL); assert(BC_ENABLE_EXTRA_MATH || base >= BC_NUM_MIN_BASE); bc_num_printNewline(); if (BC_NUM_ZERO(n)) bc_num_printHex(0, 1, false); else if (base == BC_BASE) bc_num_printDecimal(n); #if BC_ENABLE_EXTRA_MATH else if (base == 0 || base == 1) bc_num_printExponent(n, base != 0); #endif // BC_ENABLE_EXTRA_MATH else bc_num_printBase(n, base); if (newline) bc_num_putchar('\n'); } void bc_num_bigdig2(const BcNum *restrict n, BcBigDig *result) { // This function returns no errors because it's guaranteed to succeed if // its preconditions are met. Those preconditions include both parameters // being non-NULL, n being non-negative, and n being less than vm.max. If // all of that is true, then we can just convert without worrying about // negative errors or overflow. BcBigDig r = 0; size_t nrdx = BC_NUM_RDX_VAL(n); assert(n != NULL && result != NULL); assert(!BC_NUM_NEG(n)); assert(bc_num_cmp(n, &vm.max) < 0); assert(n->len - nrdx <= 3); // There is a small speed win from unrolling the loop here, and since it // only adds 53 bytes, I decided that it was worth it. switch (n->len - nrdx) { case 3: { r = (BcBigDig) n->num[nrdx + 2]; } // Fallthrough. BC_FALLTHROUGH case 2: { r = r * BC_BASE_POW + (BcBigDig) n->num[nrdx + 1]; } // Fallthrough. BC_FALLTHROUGH case 1: { r = r * BC_BASE_POW + (BcBigDig) n->num[nrdx]; } } *result = r; } void bc_num_bigdig(const BcNum *restrict n, BcBigDig *result) { assert(n != NULL && result != NULL); if (BC_ERR(BC_NUM_NEG(n))) bc_vm_err(BC_ERR_MATH_NEGATIVE); if (BC_ERR(bc_num_cmp(n, &vm.max) >= 0)) bc_vm_err(BC_ERR_MATH_OVERFLOW); bc_num_bigdig2(n, result); } void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val) { BcDig *ptr; size_t i; assert(n != NULL); bc_num_zero(n); if (!val) return; bc_num_expand(n, BC_NUM_BIGDIG_LOG10); for (ptr = n->num, i = 0; val; ++i, val /= BC_BASE_POW) ptr[i] = val % BC_BASE_POW; n->len = i; } #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND void bc_num_rng(const BcNum *restrict n, BcRNG *rng) { BcNum temp, temp2, intn, frac; BcRand state1, state2, inc1, inc2; size_t nrdx = BC_NUM_RDX_VAL(n); BC_SIG_LOCK; bc_num_init(&temp, n->len); bc_num_init(&temp2, n->len); bc_num_init(&frac, nrdx); bc_num_init(&intn, bc_num_int(n)); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; assert(BC_NUM_RDX_VALID_NP(vm.max)); memcpy(frac.num, n->num, BC_NUM_SIZE(nrdx)); frac.len = nrdx; BC_NUM_RDX_SET_NP(frac, nrdx); frac.scale = n->scale; assert(BC_NUM_RDX_VALID_NP(frac)); assert(BC_NUM_RDX_VALID_NP(vm.max2)); bc_num_mul(&frac, &vm.max2, &temp, 0); bc_num_truncate(&temp, temp.scale); bc_num_copy(&frac, &temp); memcpy(intn.num, n->num + nrdx, BC_NUM_SIZE(bc_num_int(n))); intn.len = bc_num_int(n); // This assert is here because it has to be true. It is also here to justify // the use of BC_ERR_SIGNAL_ONLY() on each of the divmod's and mod's below. assert(BC_NUM_NONZERO(&vm.max)); if (BC_NUM_NONZERO(&frac)) { bc_num_divmod(&frac, &vm.max, &temp, &temp2, 0); // frac is guaranteed to be smaller than vm.max * vm.max (pow). // This means that when dividing frac by vm.max, as above, the // quotient and remainder are both guaranteed to be less than vm.max, // which means we can use bc_num_bigdig2() here and not worry about // overflow. bc_num_bigdig2(&temp2, (BcBigDig*) &state1); bc_num_bigdig2(&temp, (BcBigDig*) &state2); } else state1 = state2 = 0; if (BC_NUM_NONZERO(&intn)) { bc_num_divmod(&intn, &vm.max, &temp, &temp2, 0); // Because temp2 is the mod of vm.max, from above, it is guaranteed // to be small enough to use bc_num_bigdig2(). bc_num_bigdig2(&temp2, (BcBigDig*) &inc1); if (bc_num_cmp(&temp, &vm.max) >= 0) { bc_num_copy(&temp2, &temp); bc_num_mod(&temp2, &vm.max, &temp, 0); } // The if statement above ensures that temp is less than vm.max, which // means that we can use bc_num_bigdig2() here. bc_num_bigdig2(&temp, (BcBigDig*) &inc2); } else inc1 = inc2 = 0; bc_rand_seed(rng, state1, state2, inc1, inc2); err: BC_SIG_MAYLOCK; bc_num_free(&intn); bc_num_free(&frac); bc_num_free(&temp2); bc_num_free(&temp); BC_LONGJMP_CONT; } void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) { BcRand s1, s2, i1, i2; BcNum conv, temp1, temp2, temp3; BcDig temp1_num[BC_RAND_NUM_SIZE], temp2_num[BC_RAND_NUM_SIZE]; BcDig conv_num[BC_NUM_BIGDIG_LOG10]; BC_SIG_LOCK; bc_num_init(&temp3, 2 * BC_RAND_NUM_SIZE); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_setup(&temp1, temp1_num, sizeof(temp1_num) / sizeof(BcDig)); bc_num_setup(&temp2, temp2_num, sizeof(temp2_num) / sizeof(BcDig)); bc_num_setup(&conv, conv_num, sizeof(conv_num) / sizeof(BcDig)); // This assert is here because it has to be true. It is also here to justify // the assumption that vm.max2 is not zero. assert(BC_NUM_NONZERO(&vm.max)); // Because this is true, we can just use BC_ERR_SIGNAL_ONLY() below when // dividing by vm.max2. assert(BC_NUM_NONZERO(&vm.max2)); bc_rand_getRands(rng, &s1, &s2, &i1, &i2); bc_num_bigdig2num(&conv, (BcBigDig) s2); assert(BC_NUM_RDX_VALID_NP(conv)); bc_num_mul(&conv, &vm.max, &temp1, 0); bc_num_bigdig2num(&conv, (BcBigDig) s1); bc_num_add(&conv, &temp1, &temp2, 0); bc_num_div(&temp2, &vm.max2, &temp3, BC_RAND_STATE_BITS); bc_num_bigdig2num(&conv, (BcBigDig) i2); assert(BC_NUM_RDX_VALID_NP(conv)); bc_num_mul(&conv, &vm.max, &temp1, 0); bc_num_bigdig2num(&conv, (BcBigDig) i1); bc_num_add(&conv, &temp1, &temp2, 0); bc_num_add(&temp2, &temp3, n, 0); assert(BC_NUM_RDX_VALID(n)); err: BC_SIG_MAYLOCK; bc_num_free(&temp3); BC_LONGJMP_CONT; } void bc_num_irand(const BcNum *restrict a, BcNum *restrict b, BcRNG *restrict rng) { BcRand r; BcBigDig modl; BcNum pow, pow2, cp, cp2, mod, temp1, temp2, rand; BcNum *p1, *p2, *t1, *t2, *c1, *c2, *tmp; BcDig rand_num[BC_NUM_BIGDIG_LOG10]; bool carry; ssize_t cmp; assert(a != b); if (BC_ERR(BC_NUM_NEG(a))) bc_vm_err(BC_ERR_MATH_NEGATIVE); if (BC_ERR(BC_NUM_RDX_VAL(a))) bc_vm_err(BC_ERR_MATH_NON_INTEGER); if (BC_NUM_ZERO(a) || BC_NUM_ONE(a)) return; cmp = bc_num_cmp(a, &vm.max); if (cmp <= 0) { BcRand bits = 0; if (cmp < 0) bc_num_bigdig2(a, (BcBigDig*) &bits); // This condition means that bits is a power of 2. In that case, we // can just grab a full-size int and mask out the unneeded bits. // Also, this condition says that 0 is a power of 2, which works for // us, since a value of 0 means a == rng->max. The bitmask will mask // nothing in that case as well. if (!(bits & (bits - 1))) r = bc_rand_int(rng) & (bits - 1); else r = bc_rand_bounded(rng, bits); // We made sure that r is less than vm.max, // so we can use bc_num_bigdig2() here. bc_num_bigdig2num(b, r); return; } // In the case where a is less than rng->max, we have to make sure we have // an exclusive bound. This ensures that it happens. (See below.) carry = (cmp < 0); BC_SIG_LOCK; bc_num_createCopy(&cp, a); bc_num_init(&cp2, cp.len); bc_num_init(&mod, BC_NUM_BIGDIG_LOG10); bc_num_init(&temp1, BC_NUM_DEF_SIZE); bc_num_init(&temp2, BC_NUM_DEF_SIZE); bc_num_init(&pow2, BC_NUM_DEF_SIZE); bc_num_init(&pow, BC_NUM_DEF_SIZE); bc_num_one(&pow); bc_num_setup(&rand, rand_num, sizeof(rand_num) / sizeof(BcDig)); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; p1 = &pow; p2 = &pow2; t1 = &temp1; t2 = &temp2; c1 = &cp; c2 = &cp2; // This assert is here because it has to be true. It is also here to justify // the use of BC_ERR_SIGNAL_ONLY() on each of the divmod's and mod's below. assert(BC_NUM_NONZERO(&vm.max)); while (BC_NUM_NONZERO(c1)) { bc_num_divmod(c1, &vm.max, c2, &mod, 0); // Because mod is the mod of vm.max, it is guaranteed to be smaller, // which means we can use bc_num_bigdig2() here. bc_num_bigdig(&mod, &modl); if (bc_num_cmp(c1, &vm.max) < 0) { // In this case, if there is no carry, then we know we can generate // an integer *equal* to modl. Thus, we add one if there is no // carry. Otherwise, we add zero, and we are still bounded properly. // Since the last portion is guaranteed to be greater than 1, we // know modl isn't 0 unless there is no carry. modl += !carry; if (modl == 1) r = 0; else if (!modl) r = bc_rand_int(rng); else r = bc_rand_bounded(rng, (BcRand) modl); } else { if (modl) modl -= carry; r = bc_rand_int(rng); carry = (r >= (BcRand) modl); } bc_num_bigdig2num(&rand, r); assert(BC_NUM_RDX_VALID_NP(rand)); assert(BC_NUM_RDX_VALID(p1)); bc_num_mul(&rand, p1, p2, 0); bc_num_add(p2, t1, t2, 0); if (BC_NUM_NONZERO(c2)) { assert(BC_NUM_RDX_VALID_NP(vm.max)); assert(BC_NUM_RDX_VALID(p1)); bc_num_mul(&vm.max, p1, p2, 0); tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } else c1 = c2; tmp = t1; t1 = t2; t2 = tmp; } bc_num_copy(b, t1); bc_num_clean(b); assert(BC_NUM_RDX_VALID(b)); err: BC_SIG_MAYLOCK; bc_num_free(&pow); bc_num_free(&pow2); bc_num_free(&temp2); bc_num_free(&temp1); bc_num_free(&mod); bc_num_free(&cp2); bc_num_free(&cp); BC_LONGJMP_CONT; } #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND size_t bc_num_addReq(const BcNum *a, const BcNum *b, size_t scale) { size_t aint, bint, ardx, brdx; BC_UNUSED(scale); ardx = BC_NUM_RDX_VAL(a); aint = bc_num_int(a); assert(aint <= a->len && ardx <= a->len); brdx = BC_NUM_RDX_VAL(b); bint = bc_num_int(b); assert(bint <= b->len && brdx <= b->len); ardx = BC_MAX(ardx, brdx); aint = BC_MAX(aint, bint); return bc_vm_growSize(bc_vm_growSize(ardx, aint), 1); } size_t bc_num_mulReq(const BcNum *a, const BcNum *b, size_t scale) { size_t max, rdx; rdx = bc_vm_growSize(BC_NUM_RDX_VAL(a), BC_NUM_RDX_VAL(b)); max = BC_NUM_RDX(scale); max = bc_vm_growSize(BC_MAX(max, rdx), 1); rdx = bc_vm_growSize(bc_vm_growSize(bc_num_int(a), bc_num_int(b)), max); return rdx; } size_t bc_num_divReq(const BcNum *a, const BcNum *b, size_t scale) { size_t max, rdx; rdx = bc_vm_growSize(BC_NUM_RDX_VAL(a), BC_NUM_RDX_VAL(b)); max = BC_NUM_RDX(scale); max = bc_vm_growSize(BC_MAX(max, rdx), 1); rdx = bc_vm_growSize(bc_num_int(a), max); return rdx; } size_t bc_num_powReq(const BcNum *a, const BcNum *b, size_t scale) { BC_UNUSED(scale); return bc_vm_growSize(bc_vm_growSize(a->len, b->len), 1); } #if BC_ENABLE_EXTRA_MATH size_t bc_num_placesReq(const BcNum *a, const BcNum *b, size_t scale) { BC_UNUSED(scale); return a->len + b->len - BC_NUM_RDX_VAL(a) - BC_NUM_RDX_VAL(b); } #endif // BC_ENABLE_EXTRA_MATH void bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, false, bc_num_as, bc_num_addReq(a, b, scale)); } void bc_num_sub(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, true, bc_num_as, bc_num_addReq(a, b, scale)); } void bc_num_mul(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_m, bc_num_mulReq(a, b, scale)); } void bc_num_div(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_d, bc_num_divReq(a, b, scale)); } void bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_rem, bc_num_divReq(a, b, scale)); } void bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_p, bc_num_powReq(a, b, scale)); } #if BC_ENABLE_EXTRA_MATH void bc_num_places(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_place, bc_num_placesReq(a, b, scale)); } void bc_num_lshift(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_left, bc_num_placesReq(a, b, scale)); } void bc_num_rshift(BcNum *a, BcNum *b, BcNum *c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_right, bc_num_placesReq(a, b, scale)); } #endif // BC_ENABLE_EXTRA_MATH void bc_num_sqrt(BcNum *restrict a, BcNum *restrict b, size_t scale) { BcNum num1, num2, half, f, fprime, *x0, *x1, *temp; size_t pow, len, rdx, req, resscale; BcDig half_digs[1]; assert(a != NULL && b != NULL && a != b); if (BC_ERR(BC_NUM_NEG(a))) bc_vm_err(BC_ERR_MATH_NEGATIVE); if (a->scale > scale) scale = a->scale; len = bc_vm_growSize(bc_num_intDigits(a), 1); rdx = BC_NUM_RDX(scale); req = bc_vm_growSize(BC_MAX(rdx, BC_NUM_RDX_VAL(a)), len >> 1); BC_SIG_LOCK; bc_num_init(b, bc_vm_growSize(req, 1)); BC_SIG_UNLOCK; assert(a != NULL && b != NULL && a != b); assert(a->num != NULL && b->num != NULL); if (BC_NUM_ZERO(a)) { bc_num_setToZero(b, scale); return; } if (BC_NUM_ONE(a)) { bc_num_one(b); bc_num_extend(b, scale); return; } rdx = BC_NUM_RDX(scale); rdx = BC_MAX(rdx, BC_NUM_RDX_VAL(a)); len = bc_vm_growSize(a->len, rdx); BC_SIG_LOCK; bc_num_init(&num1, len); bc_num_init(&num2, len); bc_num_setup(&half, half_digs, sizeof(half_digs) / sizeof(BcDig)); bc_num_one(&half); half.num[0] = BC_BASE_POW / 2; half.len = 1; BC_NUM_RDX_SET_NP(half, 1); half.scale = 1; bc_num_init(&f, len); bc_num_init(&fprime, len); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; x0 = &num1; x1 = &num2; bc_num_one(x0); pow = bc_num_intDigits(a); if (pow) { if (pow & 1) x0->num[0] = 2; else x0->num[0] = 6; pow -= 2 - (pow & 1); bc_num_shiftLeft(x0, pow / 2); } // I can set the rdx here directly because neg should be false. x0->scale = x0->rdx = 0; resscale = (scale + BC_BASE_DIGS) + 2; while (bc_num_cmp(x1, x0)) { assert(BC_NUM_NONZERO(x0)); bc_num_div(a, x0, &f, resscale); bc_num_add(x0, &f, &fprime, resscale); assert(BC_NUM_RDX_VALID_NP(fprime)); assert(BC_NUM_RDX_VALID_NP(half)); bc_num_mul(&fprime, &half, x1, resscale); temp = x0; x0 = x1; x1 = temp; } bc_num_copy(b, x0); if (b->scale > scale) bc_num_truncate(b, b->scale - scale); assert(!BC_NUM_NEG(b) || BC_NUM_NONZERO(b)); assert(BC_NUM_RDX_VALID(b)); assert(BC_NUM_RDX_VAL(b) <= b->len || !b->len); assert(!b->len || b->num[b->len - 1] || BC_NUM_RDX_VAL(b) == b->len); err: BC_SIG_MAYLOCK; bc_num_free(&fprime); bc_num_free(&f); bc_num_free(&num2); bc_num_free(&num1); BC_LONGJMP_CONT; } void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale) { size_t ts, len; BcNum *ptr_a, num2; bool init = false; ts = BC_MAX(scale + b->scale, a->scale); len = bc_num_mulReq(a, b, ts); assert(a != NULL && b != NULL && c != NULL && d != NULL); assert(c != d && a != d && b != d && b != c); if (c == a) { memcpy(&num2, c, sizeof(BcNum)); ptr_a = &num2; BC_SIG_LOCK; bc_num_init(c, len); init = true; BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; } else { ptr_a = a; bc_num_expand(c, len); } if (BC_NUM_NONZERO(a) && !BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b) && b->len == 1 && !scale) { BcBigDig rem; bc_num_divArray(ptr_a, (BcBigDig) b->num[0], c, &rem); assert(rem < BC_BASE_POW); d->num[0] = (BcDig) rem; d->len = (rem != 0); } else bc_num_r(ptr_a, b, c, d, scale, ts); assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VALID(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); assert(!BC_NUM_NEG(d) || BC_NUM_NONZERO(d)); assert(BC_NUM_RDX_VALID(d)); assert(BC_NUM_RDX_VAL(d) <= d->len || !d->len); assert(!d->len || d->num[d->len - 1] || BC_NUM_RDX_VAL(d) == d->len); err: if (init) { BC_SIG_MAYLOCK; bc_num_free(&num2); BC_LONGJMP_CONT; } } #if DC_ENABLED void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d) { BcNum base, exp, two, temp; BcDig two_digs[2]; assert(a != NULL && b != NULL && c != NULL && d != NULL); assert(a != d && b != d && c != d); if (BC_ERR(BC_NUM_ZERO(c))) bc_vm_err(BC_ERR_MATH_DIVIDE_BY_ZERO); if (BC_ERR(BC_NUM_NEG(b))) bc_vm_err(BC_ERR_MATH_NEGATIVE); if (BC_ERR(BC_NUM_RDX_VAL(a) || BC_NUM_RDX_VAL(b) || BC_NUM_RDX_VAL(c))) bc_vm_err(BC_ERR_MATH_NON_INTEGER); bc_num_expand(d, c->len); BC_SIG_LOCK; bc_num_init(&base, c->len); bc_num_setup(&two, two_digs, sizeof(two_digs) / sizeof(BcDig)); bc_num_init(&temp, b->len + 1); bc_num_createCopy(&exp, b); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_one(&two); two.num[0] = 2; bc_num_one(d); // We already checked for 0. bc_num_rem(a, c, &base, 0); while (BC_NUM_NONZERO(&exp)) { // Num two cannot be 0, so no errors. bc_num_divmod(&exp, &two, &exp, &temp, 0); if (BC_NUM_ONE(&temp) && !BC_NUM_NEG_NP(temp)) { assert(BC_NUM_RDX_VALID(d)); assert(BC_NUM_RDX_VALID_NP(base)); bc_num_mul(d, &base, &temp, 0); // We already checked for 0. bc_num_rem(&temp, c, d, 0); } assert(BC_NUM_RDX_VALID_NP(base)); bc_num_mul(&base, &base, &temp, 0); // We already checked for 0. bc_num_rem(&temp, c, &base, 0); } err: BC_SIG_MAYLOCK; bc_num_free(&exp); bc_num_free(&temp); bc_num_free(&base); BC_LONGJMP_CONT; assert(!BC_NUM_NEG(d) || d->len); assert(BC_NUM_RDX_VALID(d)); assert(!d->len || d->num[d->len - 1] || BC_NUM_RDX_VAL(d) == d->len); } #endif // DC_ENABLED #if BC_DEBUG_CODE void bc_num_printDebug(const BcNum *n, const char *name, bool emptyline) { bc_file_puts(&vm.fout, name); bc_file_puts(&vm.fout, ": "); bc_num_printDecimal(n); bc_file_putchar(&vm.fout, '\n'); if (emptyline) bc_file_putchar(&vm.fout, '\n'); vm.nchars = 0; } void bc_num_printDigs(const BcDig *n, size_t len, bool emptyline) { size_t i; for (i = len - 1; i < len; --i) bc_file_printf(&vm.fout, " %lu", (unsigned long) n[i]); bc_file_putchar(&vm.fout, '\n'); if (emptyline) bc_file_putchar(&vm.fout, '\n'); vm.nchars = 0; } void bc_num_printWithDigs(const BcNum *n, const char *name, bool emptyline) { bc_file_puts(&vm.fout, name); bc_file_printf(&vm.fout, " len: %zu, rdx: %zu, scale: %zu\n", name, n->len, BC_NUM_RDX_VAL(n), n->scale); bc_num_printDigs(n->num, n->len, emptyline); } void bc_num_dump(const char *varname, const BcNum *n) { ulong i, scale = n->scale; bc_file_printf(&vm.ferr, "\n%s = %s", varname, n->len ? (BC_NUM_NEG(n) ? "-" : "+") : "0 "); for (i = n->len - 1; i < n->len; --i) { if (i + 1 == BC_NUM_RDX_VAL(n)) bc_file_puts(&vm.ferr, ". "); if (scale / BC_BASE_DIGS != BC_NUM_RDX_VAL(n) - i - 1) bc_file_printf(&vm.ferr, "%lu ", (unsigned long) n->num[i]); else { int mod = scale % BC_BASE_DIGS; int d = BC_BASE_DIGS - mod; BcDig div; if (mod != 0) { div = n->num[i] / ((BcDig) bc_num_pow10[(ulong) d]); bc_file_printf(&vm.ferr, "%lu", (unsigned long) div); } div = n->num[i] % ((BcDig) bc_num_pow10[(ulong) d]); bc_file_printf(&vm.ferr, " ' %lu ", (unsigned long) div); } } bc_file_printf(&vm.ferr, "(%zu | %zu.%zu / %zu) %lu\n", n->scale, n->len, BC_NUM_RDX_VAL(n), n->cap, (unsigned long) (void*) n->num); } #endif // BC_DEBUG_CODE diff --git a/contrib/bc/tests/bc/length.txt b/contrib/bc/tests/bc/length.txt index 5461f76cbf59..feb4134ffabd 100644 --- a/contrib/bc/tests/bc/length.txt +++ b/contrib/bc/tests/bc/length.txt @@ -1,129 +1,132 @@ length(0) +length(0.0000) +length(0.00000000) +length(0.00000000000) length(1) length(12) length(123) length(1234) length(12345) length(123456) length(1234567) length(12345678) length(123456789) length(1234567890) length(1.0) length(12.0) length(123.0) length(1234.0) length(12345.0) length(123456.0) length(1234567.0) length(12345678.0) length(123456789.0) length(1234567890.0) length(.1) length(.12) length(.123) length(.1234) length(.12345) length(.123456) length(.1234567) length(.12345678) length(.123456789) length(.1234567890) length(.01) length(.012) length(.0123) length(.01234) length(.012345) length(.0123456) length(.01234567) length(.012345678) length(.0123456789) length(.01234567890) length(.001) length(.0012) length(.00123) length(.001234) length(.0012345) length(.00123456) length(.001234567) length(.0012345678) length(.00123456789) length(.001234567890) length(.0001) length(.00012) length(.000123) length(.0001234) length(.00012345) length(.000123456) length(.0001234567) length(.00012345678) length(.000123456789) length(.0001234567890) length(.00001) length(.000012) length(.0000123) length(.00001234) length(.000012345) length(.0000123456) length(.00001234567) length(.000012345678) length(.0000123456789) length(.00001234567890) length(.000001) length(.0000012) length(.00000123) length(.000001234) length(.0000012345) length(.00000123456) length(.000001234567) length(.0000012345678) length(.00000123456789) length(.000001234567890) length(.0000001) length(.00000012) length(.000000123) length(.0000001234) length(.00000012345) length(.000000123456) length(.0000001234567) length(.00000012345678) length(.000000123456789) length(.0000001234567890) length(.00000001) length(.000000012) length(.0000000123) length(.00000001234) length(.000000012345) length(.0000000123456) length(.00000001234567) length(.000000012345678) length(.0000000123456789) length(.00000001234567890) length(.000000001) length(.0000000012) length(.00000000123) length(.000000001234) length(.0000000012345) length(.00000000123456) length(.000000001234567) length(.0000000012345678) length(.00000000123456789) length(.000000001234567890) length(.0000000001) length(.00000000012) length(.000000000123) length(.0000000001234) length(.00000000012345) length(.000000000123456) length(.0000000001234567) length(.00000000012345678) length(.000000000123456789) length(.0000000001234567890) length(289.29837) length(2893.00000) length(289.0) length(1802973.0000000238) length(.000000000000000093182394080000000000) a[0] = 0 a[5] = 0 length(a[]) diff --git a/contrib/bc/tests/bc/length_results.txt b/contrib/bc/tests/bc/length_results.txt index 53a58e2be678..3501dea2a063 100644 --- a/contrib/bc/tests/bc/length_results.txt +++ b/contrib/bc/tests/bc/length_results.txt @@ -1,127 +1,130 @@ -0 +1 +4 +8 +11 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 8 9 4 17 20 6 diff --git a/contrib/bc/tests/bc/lib2.txt b/contrib/bc/tests/bc/lib2.txt index 9fdf50d06141..076e62b8ea61 100644 --- a/contrib/bc/tests/bc/lib2.txt +++ b/contrib/bc/tests/bc/lib2.txt @@ -1,463 +1,469 @@ p(2, 8.0000) p(2, 8.0001) p(2, -8.0001) r(0, 0) r(0, 1) r(0, 100) r(1, 0) r(1, 3) r(1.4, 0) r(1.5, 0) r(34.45, 2) r(64.1223, 4) r(283.1983893, 6) r(283.1983895, 6) r(283.1983899, 6) r(99.999999999, 5) r(-1, 0) r(-1, 3) r(-1.4, 0) r(-1.5, 0) r(-34.45, 2) r(-64.1223, 4) r(-283.1983893, 6) r(-283.1983895, 6) r(-283.1983899, 6) r(-99.999999999, 5) ceil(0, 0) ceil(0, 1) ceil(0, 100) ceil(1, 0) ceil(1, 3) ceil(1.4, 0) ceil(1.5, 0) ceil(34.45, 2) ceil(64.1223, 4) ceil(283.1983893, 6) ceil(283.1983895, 6) ceil(283.1983899, 6) ceil(99.999999999, 5) ceil(-1, 0) ceil(-1, 3) ceil(-1.4, 0) ceil(-1.5, 0) ceil(-34.45, 2) ceil(-64.1223, 4) ceil(-283.1983893, 6) ceil(-283.1983895, 6) ceil(-283.1983899, 6) ceil(-99.999999999, 5) ceil(8770735.0705156250000000000, 0) l2(0) l2(1) l2(2) l2(7) l2(7.9999999999999999999999) l2(8) l10(0) l10(1) l10(2) l10(5) l10(9) l10(9.999999999999999999999) l10(10) l10(11) l10(99) l10(99.99999999999999999999) l10(100) l2(-1) l2(-2) l2(-7) l2(-7.9999999999999999999999) l2(-8) l10(-1) l10(-2) l10(-5) l10(-9) l10(-9.999999999999999999999) l10(-10) l10(-11) l10(-99) l10(-99.99999999999999999999) l10(-100) cbrt(27) cbrt(-27) cbrt(4096) cbrt(-4096) +root(0, 3) +root(0, 4) +root(0, 5) +root(0.0000000000000, 3) +root(0.0000000000000, 4) +root(0.0000000000000, 5) root(16, 4) root(3125, 5) root(-3125, 5) ubytes(0) ubytes(1) ubytes(2) ubytes(254) ubytes(255) ubytes(256) ubytes(65535) ubytes(65536) ubytes(131072) ubytes(4294967295) ubytes(4294967296) ubytes(18446744073709551615) ubytes(18446744073709551616) sbytes(0) sbytes(1) sbytes(-1) sbytes(2) sbytes(127) sbytes(128) sbytes(-127) sbytes(-128) sbytes(-129) sbytes(254) sbytes(255) sbytes(256) sbytes(32767) sbytes(32768) sbytes(-32767) sbytes(-32768) sbytes(65535) sbytes(65536) sbytes(131072) sbytes(2147483647) sbytes(2147483648) sbytes(2147483649) sbytes(-2147483647) sbytes(-2147483648) sbytes(-2147483649) sbytes(4294967295) sbytes(4294967296) sbytes(9223372036854775807) sbytes(9223372036854775808) sbytes(9223372036854775809) sbytes(-9223372036854775807) sbytes(-9223372036854775808) sbytes(-9223372036854775809) pi(0) pi(1) pi(2) pi(5) pi(100) p=pi(100) t(0) t(1) t(-1) t(2) t(-2) t(3) t(-3) t(p) t(-p) t(p/2) t(-p/2) t(p/3) t(-p/3) t(p/4) t(-p/4) t(p/5) t(-p/5) t(p/6) t(-p/6) t(p/7) t(-p/7) t(p/8) t(-p/8) t(p/9) t(-p/9) t(p/10) t(-p/10) t(p/15) t(-p/15) a2(0, 1) a2(1, 1) a2(2, 1) a2(1, 2) a2(0, -1) a2(1, -1) a2(2, -1) a2(1, -2) a2(-1, 1) a2(-2, 1) a2(-1, 2) a2(-1, -1) a2(-2, -1) a2(-1, -2) a2(1, 0) a2(2, 0) a2(-1, 0) a2(-2, 0) r2d(p) r2d(2 * p) r2d(p / 2) r2d(p / 4) r2d(p / 3) r2d(p / 5) r2d(p / 6) r2d(p / 10) r2d(-p) r2d(2 * -p) r2d(-p / 2) r2d(-p / 4) r2d(-p / 3) r2d(-p / 5) r2d(-p / 6) r2d(-p / 10) d2r(180) d2r(360) d2r(90) d2r(45) d2r(120) d2r(72) d2r(60) d2r(36) d2r(-180) d2r(-360) d2r(-90) d2r(-45) d2r(-120) d2r(-72) d2r(-60) d2r(-36) f(0) f(1) f(2) f(3) f(4) f(5) perm(10, 2) comb(10, 2) perm(6, 2) comb(6, 2) perm(12, 10) comb(12, 10) perm(24, 15) comb(24, 15) binary(0) hex(0) binary(1) hex(1) binary(2) hex(2) binary(15) hex(15) binary(16) hex(16) uint(0) int(0) uint(1) int(1) int(-1) uint(127) int(127) int(-127) uint(128) int(128) int(-128) uint(129) int(129) int(-129) uint(255) int(255) int(-255) uint(256) int(256) int(-256) uint(32767) int(32767) int(-32767) uint(32768) int(32768) int(-32768) uint(32769) int(32769) int(-32769) uint(65535) int(65535) int(-65535) uint(65536) int(65536) int(-65536) uint(2147483647) int(2147483647) int(-2147483647) uint(2147483648) int(2147483648) int(-2147483648) uint(2147483649) int(2147483649) int(-2147483649) uint(4294967295) int(4294967295) int(-4294967295) uint(4294967296) int(4294967296) int(-4294967296) uint8(0) int8(0) uint16(0) int16(0) uint32(0) int32(0) uint64(0) int64(0) uint8(1) int8(1) int8(-1) uint16(1) int16(1) int16(-1) uint32(1) int32(1) int32(-1) uint64(1) int64(1) int64(-1) uint8(127) int8(127) int8(-127) uint16(127) int16(127) int16(-127) uint32(127) int32(127) int32(-127) uint64(127) int64(127) int64(-127) uint8(128) int8(128) int8(-128) uint16(128) int16(128) int16(-128) uint32(128) int32(128) int32(-128) uint64(128) int64(128) int64(-128) uint8(129) int8(129) int8(-129) uint16(129) int16(129) int16(-129) uint32(129) int32(129) int32(-129) uint64(129) int64(129) int64(-129) uint8(255) int8(255) int8(-255) uint16(255) int16(255) int16(-255) uint32(255) int32(255) int32(-255) uint64(255) int64(255) int64(-255) uint8(256) int8(256) int8(-256) uint16(256) int16(256) int16(-256) uint32(256) int32(256) int32(-256) uint64(256) int64(256) int64(-256) uint16(32767) int16(32767) int16(-32767) uint32(32767) int32(32767) int32(-32767) uint64(32767) int64(32767) int64(-32767) uint16(32768) int16(32768) int16(-32768) uint32(32768) int32(32768) int32(-32768) uint64(32768) int64(32768) int64(-32768) uint16(32769) int16(32769) int16(-32769) uint32(32769) int32(32769) int32(-32769) uint64(32769) int64(32769) int64(-32769) uint16(65535) int16(65535) int16(-65535) uint32(65535) int32(65535) int32(-65535) uint64(65535) int64(65535) int64(-65535) uint16(65536) int16(65536) int16(-65536) uint32(65536) int32(65536) int32(-65536) uint64(65536) int64(65536) int64(-65536) uint32(2147483647) int32(2147483647) int32(-2147483647) uint64(2147483647) int64(2147483647) int64(-2147483647) uint32(2147483648) int32(2147483648) int32(-2147483648) uint64(2147483648) int64(2147483648) int64(-2147483648) uint32(2147483649) int32(2147483649) int32(-2147483649) uint64(2147483649) int64(2147483649) int64(-2147483649) uint32(4294967295) int32(4294967295) int32(-4294967295) uint64(4294967295) int64(4294967295) int64(-4294967295) uint32(4294967296) int32(4294967296) int32(-4294967296) uint64(4294967296) int64(4294967296) int64(-4294967296) uint(-3) uint(3.928375) int(4.000000) b = brand() b < 2 b >= 0 i = irand(maxrand() + 1) i <= maxrand() i >= 0 f = frand(10) scale(f) == 10 fi = ifrand(123, 28) scale(fi) == 28 fi < 128 diff --git a/contrib/bc/tests/bc/lib2_results.txt b/contrib/bc/tests/bc/lib2_results.txt index ca5a37cfce0a..ca790604e07b 100644 --- a/contrib/bc/tests/bc/lib2_results.txt +++ b/contrib/bc/tests/bc/lib2_results.txt @@ -1,698 +1,704 @@ 256.00000000000000000000 256.01774518281640169821 .00390597924876622489 0 0 0 1 1.000 1 2 34.45 64.1223 283.198389 283.198390 283.198390 100.00000 -1 -1.000 -1 -2 -34.45 -64.1223 -283.198389 -283.198390 -283.198390 -100.00000 0 0 0 1 1.000 2 2 34.45 64.1223 283.198390 283.198390 283.198390 100.00000 -1 -1.000 -2 -2 -34.45 -64.1223 -283.198390 -283.198390 -283.198390 -100.00000 8770736 -14426950408889634073599246810018921374265.01964302164603717234 0 1.00000000000000000000 2.80735492205760410744 2.99999999999999999999 3.00000000000000000000 -4342944819032518276511289189166050822943.53857128275332257904 0 .30102999566398119521 .69897000433601880478 .95424250943932487459 .99999999999999999999 1.00000000000000000000 1.04139268515822504075 1.99563519459754991534 1.99999999999999999999 2.00000000000000000000 -14426950408889634073599246810018921374265.01964302164603717234 -14426950408889634073599246810018921374265.01964302164603717234 -14426950408889634073599246810018921374265.01964302164603717234 -144269504088896340735992468100189213742664594.88013355604393225658 -14426950408889634073599246810018921374265.01964302164603717234 -4342944819032518276511289189166050822943.53857128275332257904 -4342944819032518276511289189166050822943.53857128275332257904 -4342944819032518276511289189166050822943.53857128275332257904 -4342944819032518276511289189166050822943.53857128275332257904 -434294481903251827651128918916605082294396.66367028674257491242 -4342944819032518276511289189166050822943.53857128275332257904 -4342944819032518276511289189166050822943.53857128275332257904 -4342944819032518276511289189166050822943.53857128275332257904 -4342944819032518276511289189166050822943.53857128275332257904 -4342944819032518276511289189166050822943.53857128275332257904 3.00000000000000000000 -3.00000000000000000000 16.00000000000000000000 -16.00000000000000000000 +0 +0 +0 +0 +0 +0 2.00000000000000000000 5.00000000000000000000 -5.00000000000000000000 1 1 1 1 1 2 2 4 4 4 8 8 16 1 1 1 1 1 2 1 1 2 2 2 2 2 4 2 2 4 4 4 4 8 8 4 4 8 8 8 8 16 16 8 8 16 3 3.1 3.14 3.14159 3.141592653589793238462643383279502884197169399375105820974944592307\ 8164062862089986280348253421170679 0 1.55740772465490223050 -1.55740772465490223050 -2.18503986326151899164 2.18503986326151899164 -.14254654307427780529 .14254654307427780529 0 0 769230769230769230769.23076923076923076923 -769230769230769230769.23076923076923076923 1.73205080756887729351 -1.73205080756887729351 .99999999999999999998 -.99999999999999999998 .72654252800536088589 -.72654252800536088589 .57735026918962576449 -.57735026918962576449 .48157461880752864432 -.48157461880752864432 .41421356237309504879 -.41421356237309504879 .36397023426620236134 -.36397023426620236134 .32491969623290632614 -.32491969623290632614 .21255656167002212525 -.21255656167002212525 0 .78539816339744830961 1.10714871779409050301 .46364760900080611621 3.14159265358979323846 2.35619449019234492884 2.03444393579570273544 2.67794504458898712224 -.78539816339744830961 -1.10714871779409050301 -.46364760900080611621 -2.35619449019234492884 -2.03444393579570273544 -2.67794504458898712224 1.57079632679489661923 1.57079632679489661923 -1.57079632679489661923 -1.57079632679489661923 180.00000000000000000000 360.00000000000000000000 89.99999999999999999992 44.99999999999999999967 59.99999999999999999975 35.99999999999999999985 29.99999999999999999959 17.99999999999999999964 -180.00000000000000000000 -360.00000000000000000000 -89.99999999999999999992 -44.99999999999999999967 -59.99999999999999999975 -35.99999999999999999985 -29.99999999999999999959 -17.99999999999999999964 3.14159265358979323846 6.28318530717958647692 1.57079632679489661923 .78539816339744830961 2.09439510239319549230 1.25663706143591729538 1.04719755119659774615 .62831853071795864769 -3.14159265358979323846 -6.28318530717958647692 -1.57079632679489661923 -.78539816339744830961 -2.09439510239319549230 -1.25663706143591729538 -1.04719755119659774615 -.62831853071795864769 1 1 2 6 24 120 90 45 30 15 239500800 66 1709789466857472000 1307504 0 0 1 1 10 2 1111 F 10000 10 00000000 00 00000000 00 00000001 01 00000001 01 11111111 FF 01111111 7F 01111111 7F 10000001 81 10000000 80 00000000 10000000 00 80 10000000 80 10000001 81 00000000 10000001 00 81 11111111 01111111 FF 7F 11111111 FF 00000000 11111111 00 FF 11111111 00000001 FF 01 00000001 00000000 01 00 00000001 00000000 01 00 11111111 00000000 FF 00 01111111 11111111 7F FF 01111111 11111111 7F FF 10000000 00000001 80 01 10000000 00000000 80 00 00000000 00000000 10000000 00000000 00 00 80 00 10000000 00000000 80 00 10000000 00000001 80 01 00000000 00000000 10000000 00000001 00 00 80 01 11111111 11111111 01111111 11111111 FF FF 7F FF 11111111 11111111 FF FF 00000000 00000000 11111111 11111111 00 00 FF FF 11111111 11111111 00000000 00000001 FF FF 00 01 00000000 00000001 00000000 00000000 00 01 00 00 00000000 00000001 00000000 00000000 00 01 00 00 11111111 11111111 00000000 00000000 FF FF 00 00 01111111 11111111 11111111 11111111 7F FF FF FF 01111111 11111111 11111111 11111111 7F FF FF FF 10000000 00000000 00000000 00000001 80 00 00 01 10000000 00000000 00000000 00000000 80 00 00 00 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000\ 000 00 00 00 00 80 00 00 00 10000000 00000000 00000000 00000000 80 00 00 00 10000000 00000000 00000000 00000001 80 00 00 01 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000\ 001 00 00 00 00 80 00 00 01 11111111 11111111 11111111 11111111 01111111 11111111 11111111 11111\ 111 FF FF FF FF 7F FF FF FF 11111111 11111111 11111111 11111111 FF FF FF FF 00000000 00000000 00000000 00000000 11111111 11111111 11111111 11111\ 111 00 00 00 00 FF FF FF FF 11111111 11111111 11111111 11111111 00000000 00000000 00000000 00000\ 001 FF FF FF FF 00 00 00 01 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000\ 000 00 00 00 01 00 00 00 00 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000\ 000 00 00 00 01 00 00 00 00 11111111 11111111 11111111 11111111 00000000 00000000 00000000 00000\ 000 FF FF FF FF 00 00 00 00 00000000 00 00000000 00 00000000 00000000 00 00 00000000 00000000 00 00 00000000 00000000 00000000 00000000 00 00 00 00 00000000 00000000 00000000 00000000 00 00 00 00 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000\ 000 00 00 00 00 00 00 00 00 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000\ 000 00 00 00 00 00 00 00 00 00000001 01 00000001 01 11111111 FF 00000000 00000001 00 01 00000000 00000001 00 01 11111111 11111111 FF FF 00000000 00000000 00000000 00000001 00 00 00 01 00000000 00000000 00000000 00000001 00 00 00 01 11111111 11111111 11111111 11111111 FF FF FF FF 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000\ 001 00 00 00 00 00 00 00 01 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000\ 001 00 00 00 00 00 00 00 01 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111\ 111 FF FF FF FF FF FF FF FF 01111111 7F 01111111 7F 10000001 81 00000000 01111111 00 7F 00000000 01111111 00 7F 11111111 10000001 FF 81 00000000 00000000 00000000 01111111 00 00 00 7F 00000000 00000000 00000000 01111111 00 00 00 7F 11111111 11111111 11111111 10000001 FF FF FF 81 00000000 00000000 00000000 00000000 00000000 00000000 00000000 01111\ 111 00 00 00 00 00 00 00 7F 00000000 00000000 00000000 00000000 00000000 00000000 00000000 01111\ 111 00 00 00 00 00 00 00 7F 11111111 11111111 11111111 11111111 11111111 11111111 11111111 10000\ 001 FF FF FF FF FF FF FF 81 10000000 80 Error: 128 cannot fit into 1 signed byte(s). 10000000 80 00000000 10000000 00 80 00000000 10000000 00 80 11111111 10000000 FF 80 00000000 00000000 00000000 10000000 00 00 00 80 00000000 00000000 00000000 10000000 00 00 00 80 11111111 11111111 11111111 10000000 FF FF FF 80 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000\ 000 00 00 00 00 00 00 00 80 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000\ 000 00 00 00 00 00 00 00 80 11111111 11111111 11111111 11111111 11111111 11111111 11111111 10000\ 000 FF FF FF FF FF FF FF 80 10000001 81 Error: 129 cannot fit into 1 signed byte(s). Error: -129 cannot fit into 1 signed byte(s). 00000000 10000001 00 81 00000000 10000001 00 81 11111111 01111111 FF 7F 00000000 00000000 00000000 10000001 00 00 00 81 00000000 00000000 00000000 10000001 00 00 00 81 11111111 11111111 11111111 01111111 FF FF FF 7F 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000\ 001 00 00 00 00 00 00 00 81 00000000 00000000 00000000 00000000 00000000 00000000 00000000 10000\ 001 00 00 00 00 00 00 00 81 11111111 11111111 11111111 11111111 11111111 11111111 11111111 01111\ 111 FF FF FF FF FF FF FF 7F 11111111 FF Error: 255 cannot fit into 1 signed byte(s). Error: -255 cannot fit into 1 signed byte(s). 00000000 11111111 00 FF 00000000 11111111 00 FF 11111111 00000001 FF 01 00000000 00000000 00000000 11111111 00 00 00 FF 00000000 00000000 00000000 11111111 00 00 00 FF 11111111 11111111 11111111 00000001 FF FF FF 01 00000000 00000000 00000000 00000000 00000000 00000000 00000000 11111\ 111 00 00 00 00 00 00 00 FF 00000000 00000000 00000000 00000000 00000000 00000000 00000000 11111\ 111 00 00 00 00 00 00 00 FF 11111111 11111111 11111111 11111111 11111111 11111111 11111111 00000\ 001 FF FF FF FF FF FF FF 01 Error: 256 cannot fit into 1 unsigned byte(s). Error: 256 cannot fit into 1 signed byte(s). Error: -256 cannot fit into 1 signed byte(s). 00000001 00000000 01 00 00000001 00000000 01 00 11111111 00000000 FF 00 00000000 00000000 00000001 00000000 00 00 01 00 00000000 00000000 00000001 00000000 00 00 01 00 11111111 11111111 11111111 00000000 FF FF FF 00 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000\ 000 00 00 00 00 00 00 01 00 00000000 00000000 00000000 00000000 00000000 00000000 00000001 00000\ 000 00 00 00 00 00 00 01 00 11111111 11111111 11111111 11111111 11111111 11111111 11111111 00000\ 000 FF FF FF FF FF FF FF 00 01111111 11111111 7F FF 01111111 11111111 7F FF 10000000 00000001 80 01 00000000 00000000 01111111 11111111 00 00 7F FF 00000000 00000000 01111111 11111111 00 00 7F FF 11111111 11111111 10000000 00000001 FF FF 80 01 00000000 00000000 00000000 00000000 00000000 00000000 01111111 11111\ 111 00 00 00 00 00 00 7F FF 00000000 00000000 00000000 00000000 00000000 00000000 01111111 11111\ 111 00 00 00 00 00 00 7F FF 11111111 11111111 11111111 11111111 11111111 11111111 10000000 00000\ 001 FF FF FF FF FF FF 80 01 10000000 00000000 80 00 Error: 32768 cannot fit into 2 signed byte(s). 10000000 00000000 80 00 00000000 00000000 10000000 00000000 00 00 80 00 00000000 00000000 10000000 00000000 00 00 80 00 11111111 11111111 10000000 00000000 FF FF 80 00 00000000 00000000 00000000 00000000 00000000 00000000 10000000 00000\ 000 00 00 00 00 00 00 80 00 00000000 00000000 00000000 00000000 00000000 00000000 10000000 00000\ 000 00 00 00 00 00 00 80 00 11111111 11111111 11111111 11111111 11111111 11111111 10000000 00000\ 000 FF FF FF FF FF FF 80 00 10000000 00000001 80 01 Error: 32769 cannot fit into 2 signed byte(s). Error: -32769 cannot fit into 2 signed byte(s). 00000000 00000000 10000000 00000001 00 00 80 01 00000000 00000000 10000000 00000001 00 00 80 01 11111111 11111111 01111111 11111111 FF FF 7F FF 00000000 00000000 00000000 00000000 00000000 00000000 10000000 00000\ 001 00 00 00 00 00 00 80 01 00000000 00000000 00000000 00000000 00000000 00000000 10000000 00000\ 001 00 00 00 00 00 00 80 01 11111111 11111111 11111111 11111111 11111111 11111111 01111111 11111\ 111 FF FF FF FF FF FF 7F FF 11111111 11111111 FF FF Error: 65535 cannot fit into 2 signed byte(s). Error: -65535 cannot fit into 2 signed byte(s). 00000000 00000000 11111111 11111111 00 00 FF FF 00000000 00000000 11111111 11111111 00 00 FF FF 11111111 11111111 00000000 00000001 FF FF 00 01 00000000 00000000 00000000 00000000 00000000 00000000 11111111 11111\ 111 00 00 00 00 00 00 FF FF 00000000 00000000 00000000 00000000 00000000 00000000 11111111 11111\ 111 00 00 00 00 00 00 FF FF 11111111 11111111 11111111 11111111 11111111 11111111 00000000 00000\ 001 FF FF FF FF FF FF 00 01 Error: 65536 cannot fit into 2 unsigned byte(s). Error: 65536 cannot fit into 2 signed byte(s). Error: -65536 cannot fit into 2 signed byte(s). 00000000 00000001 00000000 00000000 00 01 00 00 00000000 00000001 00000000 00000000 00 01 00 00 11111111 11111111 00000000 00000000 FF FF 00 00 00000000 00000000 00000000 00000000 00000000 00000001 00000000 00000\ 000 00 00 00 00 00 01 00 00 00000000 00000000 00000000 00000000 00000000 00000001 00000000 00000\ 000 00 00 00 00 00 01 00 00 11111111 11111111 11111111 11111111 11111111 11111111 00000000 00000\ 000 FF FF FF FF FF FF 00 00 01111111 11111111 11111111 11111111 7F FF FF FF 01111111 11111111 11111111 11111111 7F FF FF FF 10000000 00000000 00000000 00000001 80 00 00 01 00000000 00000000 00000000 00000000 01111111 11111111 11111111 11111\ 111 00 00 00 00 7F FF FF FF 00000000 00000000 00000000 00000000 01111111 11111111 11111111 11111\ 111 00 00 00 00 7F FF FF FF 11111111 11111111 11111111 11111111 10000000 00000000 00000000 00000\ 001 FF FF FF FF 80 00 00 01 10000000 00000000 00000000 00000000 80 00 00 00 Error: 2147483648 cannot fit into 4 signed byte(s). 10000000 00000000 00000000 00000000 80 00 00 00 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000\ 000 00 00 00 00 80 00 00 00 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000\ 000 00 00 00 00 80 00 00 00 11111111 11111111 11111111 11111111 10000000 00000000 00000000 00000\ 000 FF FF FF FF 80 00 00 00 10000000 00000000 00000000 00000001 80 00 00 01 Error: 2147483649 cannot fit into 4 signed byte(s). Error: -2147483649 cannot fit into 4 signed byte(s). 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000\ 001 00 00 00 00 80 00 00 01 00000000 00000000 00000000 00000000 10000000 00000000 00000000 00000\ 001 00 00 00 00 80 00 00 01 11111111 11111111 11111111 11111111 01111111 11111111 11111111 11111\ 111 FF FF FF FF 7F FF FF FF 11111111 11111111 11111111 11111111 FF FF FF FF Error: 4294967295 cannot fit into 4 signed byte(s). Error: -4294967295 cannot fit into 4 signed byte(s). 00000000 00000000 00000000 00000000 11111111 11111111 11111111 11111\ 111 00 00 00 00 FF FF FF FF 00000000 00000000 00000000 00000000 11111111 11111111 11111111 11111\ 111 00 00 00 00 FF FF FF FF 11111111 11111111 11111111 11111111 00000000 00000000 00000000 00000\ 001 FF FF FF FF 00 00 00 01 Error: 4294967296 cannot fit into 4 unsigned byte(s). Error: 4294967296 cannot fit into 4 signed byte(s). Error: -4294967296 cannot fit into 4 signed byte(s). 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000\ 000 00 00 00 01 00 00 00 00 00000000 00000000 00000000 00000001 00000000 00000000 00000000 00000\ 000 00 00 00 01 00 00 00 00 11111111 11111111 11111111 11111111 00000000 00000000 00000000 00000\ 000 FF FF FF FF 00 00 00 00 Error: -3 is negative. Error: 3.928375 is not an integer. Error: 4.000000 is not an integer. 1 1 1 1 1 1 1 diff --git a/contrib/bc/tests/bc/scripts/bessel.bc b/contrib/bc/tests/bc/scripts/bessel.bc index b82eee30d19e..c2229e50bc8e 100755 --- a/contrib/bc/tests/bc/scripts/bessel.bc +++ b/contrib/bc/tests/bc/scripts/bessel.bc @@ -1,43 +1,48 @@ #! /usr/bin/bc -q t[0] = 0 t[1] = 0.5 t[2] = 1 t[3] = 1.5 t[4] = 1.74 t[5] = 2 t[6] = 3.2345 t[7] = 100 t[8] = -0.5 t[9] = -1 t[10] = -1.5 t[11] = -1.74 t[12] = -2 t[13] = -3.2345 t[14] = -100 +t[15] = 0.0000000000000000 -l = 15 +l = 16 a[0] = t[0] for (i = 1; i < l; ++i) { a[i * 2 - 1] = t[i] a[i * 2] = -t[i] } l *= 2 l -= 1 for (i = 0; i < l; ++i) { for (j = 0; j < l; ++j) { - print "j(", a[i], ", ", a[j], ")\n" + print "j(", a[i] + if (a[i] == 0 && scale(a[i]) > 0) print ".0000000000000000" + print ", ", a[j] + if (a[j] == 0 && scale(a[j]) > 0) print ".0000000000000000" + print ")\n" } } # These are specific tests that bc could not pass at one time. print "j(3, 0.75)\n" print "scale = 0; j(40, 0.75)\n" print "halt\n" halt diff --git a/contrib/bc/tests/dc/all.txt b/contrib/bc/tests/dc/all.txt index 6879541f7f1a..ec637c346ceb 100644 --- a/contrib/bc/tests/dc/all.txt +++ b/contrib/bc/tests/dc/all.txt @@ -1,22 +1,23 @@ decimal +length add subtract multiply divide modulus divmod power sqrt modexp boolean negate trunc places shift abs scientific engineering vars misc strings rand diff --git a/contrib/bc/tests/dc/length.txt b/contrib/bc/tests/dc/length.txt new file mode 100644 index 000000000000..daa960bed23b --- /dev/null +++ b/contrib/bc/tests/dc/length.txt @@ -0,0 +1,129 @@ +0ZpR +0.0000ZpR +0.00000000ZpR +0.00000000000ZpR +1ZpR +12ZpR +123ZpR +1234ZpR +12345ZpR +123456ZpR +1234567ZpR +12345678ZpR +123456789ZpR +1234567890ZpR +1.0ZpR +12.0ZpR +123.0ZpR +1234.0ZpR +12345.0ZpR +123456.0ZpR +1234567.0ZpR +12345678.0ZpR +123456789.0ZpR +1234567890.0ZpR +.1ZpR +.12ZpR +.123ZpR +.1234ZpR +.12345ZpR +.123456ZpR +.1234567ZpR +.12345678ZpR +.123456789ZpR +.1234567890ZpR +.01ZpR +.012ZpR +.0123ZpR +.01234ZpR +.012345ZpR +.0123456ZpR +.01234567ZpR +.012345678ZpR +.0123456789ZpR +.01234567890ZpR +.001ZpR +.0012ZpR +.00123ZpR +.001234ZpR +.0012345ZpR +.00123456ZpR +.001234567ZpR +.0012345678ZpR +.00123456789ZpR +.001234567890ZpR +.0001ZpR +.00012ZpR +.000123ZpR +.0001234ZpR +.00012345ZpR +.000123456ZpR +.0001234567ZpR +.00012345678ZpR +.000123456789ZpR +.0001234567890ZpR +.00001ZpR +.000012ZpR +.0000123ZpR +.00001234ZpR +.000012345ZpR +.0000123456ZpR +.00001234567ZpR +.000012345678ZpR +.0000123456789ZpR +.00001234567890ZpR +.000001ZpR +.0000012ZpR +.00000123ZpR +.000001234ZpR +.0000012345ZpR +.00000123456ZpR +.000001234567ZpR +.0000012345678ZpR +.00000123456789ZpR +.000001234567890ZpR +.0000001ZpR +.00000012ZpR +.000000123ZpR +.0000001234ZpR +.00000012345ZpR +.000000123456ZpR +.0000001234567ZpR +.00000012345678ZpR +.000000123456789ZpR +.0000001234567890ZpR +.00000001ZpR +.000000012ZpR +.0000000123ZpR +.00000001234ZpR +.000000012345ZpR +.0000000123456ZpR +.00000001234567ZpR +.000000012345678ZpR +.0000000123456789ZpR +.00000001234567890ZpR +.000000001ZpR +.0000000012ZpR +.00000000123ZpR +.000000001234ZpR +.0000000012345ZpR +.00000000123456ZpR +.000000001234567ZpR +.0000000012345678ZpR +.00000000123456789ZpR +.000000001234567890ZpR +.0000000001ZpR +.00000000012ZpR +.000000000123ZpR +.0000000001234ZpR +.00000000012345ZpR +.000000000123456ZpR +.0000000001234567ZpR +.00000000012345678ZpR +.000000000123456789ZpR +.0000000001234567890ZpR +289.29837ZpR +2893.00000ZpR +289.0ZpR +1802973.0000000238ZpR +.000000000000000093182394080000000000ZpR diff --git a/contrib/bc/tests/bc/length_results.txt b/contrib/bc/tests/dc/length_results.txt similarity index 96% copy from contrib/bc/tests/bc/length_results.txt copy to contrib/bc/tests/dc/length_results.txt index 53a58e2be678..3a79696e38b7 100644 --- a/contrib/bc/tests/bc/length_results.txt +++ b/contrib/bc/tests/dc/length_results.txt @@ -1,127 +1,129 @@ -0 +1 +4 +8 +11 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 11 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 8 9 4 17 20 -6