{
    "content": [
        {
            "type": "text",
            "text": "# bc (info)\n\n## Sections\n\n- **1 Introduction** (2 subsections)\n- **2 Basic Elements** (3 subsections)\n- **3 Expressions** (6 subsections)\n- **4 Statements** (1 subsections)\n- **5 Functions** (1 subsections)\n- **6 Examples**\n- **7 Readline and Libedit Options**\n- **8 Comparison with Other Implementations**\n- **9 Limits**\n- **10 Environment Variables**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "bc",
        "section": "",
        "mode": "info",
        "summary": null,
        "synopsis": null,
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "1 Introduction",
                "lines": 7,
                "subsections": [
                    {
                        "name": "1.1 Description",
                        "lines": 28
                    },
                    {
                        "name": "1.2 Command Line Options",
                        "lines": 22
                    }
                ]
            },
            {
                "name": "2 Basic Elements",
                "lines": 8,
                "subsections": [
                    {
                        "name": "2.1 Numbers",
                        "lines": 13
                    },
                    {
                        "name": "2.2 Variables",
                        "lines": 19
                    },
                    {
                        "name": "2.3 Comments",
                        "lines": 14
                    }
                ]
            },
            {
                "name": "3 Expressions",
                "lines": 11,
                "subsections": [
                    {
                        "name": "3.1 About Expressions and Special Variables",
                        "lines": 29
                    },
                    {
                        "name": "3.2 Basic Expressions",
                        "lines": 81
                    },
                    {
                        "name": "3.3 Relational Expressions",
                        "lines": 27
                    },
                    {
                        "name": "3.4 Boolean Expressions",
                        "lines": 16
                    },
                    {
                        "name": "3.5 Precedence",
                        "lines": 28
                    },
                    {
                        "name": "3.6 Special Expressions",
                        "lines": 30
                    }
                ]
            },
            {
                "name": "4 Statements",
                "lines": 129,
                "subsections": [
                    {
                        "name": "4.1 Pseudo Statements",
                        "lines": 17
                    }
                ]
            },
            {
                "name": "5 Functions",
                "lines": 100,
                "subsections": [
                    {
                        "name": "5.1 Math Library Functions",
                        "lines": 25
                    }
                ]
            },
            {
                "name": "6 Examples",
                "lines": 87,
                "subsections": []
            },
            {
                "name": "7 Readline and Libedit Options",
                "lines": 15,
                "subsections": []
            },
            {
                "name": "8 Comparison with Other Implementations",
                "lines": 121,
                "subsections": []
            },
            {
                "name": "9 Limits",
                "lines": 36,
                "subsections": []
            },
            {
                "name": "10 Environment Variables",
                "lines": 23,
                "subsections": []
            }
        ],
        "sections": {
            "1 Introduction": {
                "content": "* Menu:\n\n* Description::\n* Command Line Options::\n\nFile: bc.info,  Node: Description,  Next: Command Line Options,  Prev: Introduction,  Up: Introduction\n",
                "subsections": [
                    {
                        "name": "1.1 Description",
                        "content": "'bc' [ -hlwsqv ] [long-options] [ FILE ... ]\n\n'bc' is a language that supports arbitrary precision numbers with\ninteractive execution of statements.  There are some similarities in the\nsyntax to the C programming language.  A standard math library is\navailable by command line option.  If requested, the math library is\ndefined before processing any files.  'bc' starts by processing code\nfrom all the files listed on the command line in the order listed.\nAfter all files have been processed, 'bc' reads from the standard input.\nAll code is executed as it is read.  (If a file contains a command to\nhalt the processor, 'bc' will never read from the standard input.)\n\nThis version of 'bc' contains several extensions beyond traditional\n'bc' implementations and the POSIX draft standard.  Command line options\ncan cause these extensions to print a warning or to be rejected.  This\ndocument describes the language accepted by this processor.  Extensions\nwill be identified as such.\n\nThe author would like to thank Steve Sommars\n(<Steve.Sommars@att.com>) for his extensive help in testing the\nimplementation.  Many great suggestions were given.  This is a much\nbetter product due to his involvement.\n\nEmail bug reports to <bug-bc@gnu.org>.  Be sure to include the word\n\"bc\" somewhere in the \"Subject:\" field.\n\nFile: bc.info,  Node: Command Line Options,  Next: Numbers,  Prev: Description,  Up: Introduction\n"
                    },
                    {
                        "name": "1.2 Command Line Options",
                        "content": "'bc' takes the following options from the command line:\n\n'-h, --help'\nPrint the usage and exit.\n\n'-l, --mathlib'\nDefine the standard math library.\n\n'-w, --warn'\nGive warnings for extensions to POSIX 'bc'.\n\n'-s, --standard'\nProcess exactly the POSIX 'bc' language.\n\n'-q, --quiet'\nDo not print the normal GNU 'bc' welcome.\n\n'-v, --version'\nPrint the version number and copyright and quit.\n\nFile: bc.info,  Node: Basic Elements,  Next: Expressions,  Prev: Introduction,  Up: Top\n"
                    }
                ]
            },
            "2 Basic Elements": {
                "content": "* Menu:\n\n* Numbers::\n* Variables::\n* Comments::\n\nFile: bc.info,  Node: Numbers,  Next: Variables,  Prev: Command Line Options,  Up: Basic Elements\n",
                "subsections": [
                    {
                        "name": "2.1 Numbers",
                        "content": "The most basic element in 'bc' is the number.  Numbers are arbitrary\nprecision numbers.  This precision is both in the integer part and the\nfractional part.  All numbers are represented internally in decimal and\nall computation is done in decimal.  (This version truncates results\nfrom divide and multiply operations.)  There are two attributes of\nnumbers, the length and the scale.  The length is the total number of\ndigits used by 'bc' to represent a number and the scale is the total\nnumber of decimal digits after the decimal point.  For example, .000001\nhas a length of 6 and scale of 6, while 1935.000 has a length of 7 and a\nscale of 3.\n\nFile: bc.info,  Node: Variables,  Next: Comments,  Prev: Numbers,  Up: Basic Elements\n"
                    },
                    {
                        "name": "2.2 Variables",
                        "content": "Numbers are stored in two types of variables, simple variables and\narrays.  Both simple variables and array variables are named.  Names\nbegin with a letter followed by any number of letters, digits and\nunderscores.  All letters must be lower case.  (Full alphanumeric names\nare an extension.  In POSIX 'bc' all names are a single lower case\nletter.)  The type of variable is clear by the context because all array\nvariable names will be followed by brackets ( [ ] ).\n\nThere are four special variables, SCALE, IBASE, OBASE, and LAST.\nSCALE defines how some operations use digits after the decimal point.\nThe default value of SCALE is 0.  IBASE and OBASE define the conversion\nbase for input and output numbers.  The default for both input and\noutput is base 10.  LAST (an extension) is a variable that has the value\nof the last printed number.  These will be discussed in further detail\nwhere appropriate.  All of these variables may have values assigned to\nthem as well as used in expressions.\n\nFile: bc.info,  Node: Comments,  Prev: Variables,  Up: Basic Elements\n"
                    },
                    {
                        "name": "2.3 Comments",
                        "content": "Comments in 'bc' start with the characters '/*' and end with the\ncharacters '*/'.  Comments may start anywhere and appear as a single\nspace in the input.  (This causes comments to delimit other input items.\nFor example, a comment can not be found in the middle of a variable\nname.)  Comments include any newlines (end of line) between the start\nand the end of the comment.\n\nTo support the use of scripts for 'bc', a single line comment has\nbeen added as an extension.  A single line comment starts at a '#'\ncharacter and continues to the next end of the line.  The end of line\ncharacter is not part of the comment and is processed normally.\n\nFile: bc.info,  Node: Expressions,  Next: Statements,  Prev: Basic Elements,  Up: Top\n"
                    }
                ]
            },
            "3 Expressions": {
                "content": "* Menu:\n\n* About Expressions and Special Variables::\n* Basic Expressions::\n* Relational Expressions::\n* Boolean Expressions::\n* Precedence::\n* Special Expressions::\n\nFile: bc.info,  Node: About Expressions and Special Variables,  Next: Basic Expressions,  Prev: Expressions,  Up: Expressions\n",
                "subsections": [
                    {
                        "name": "3.1 About Expressions and Special Variables",
                        "content": "The numbers are manipulated by expressions and statements.  Since the\nlanguage was designed to be interactive, statements and expressions are\nexecuted as soon as possible.  There is no main program.  Instead, code\nis executed as it is encountered.  (Functions, discussed in detail\nlater, are defined when encountered.)\n\nA simple expression is just a constant.  'bc' converts constants into\ninternal decimal numbers using the current input base, specified by the\nvariable IBASE.  (There is an exception in functions.)  The legal values\nof IBASE are 2 through 36.  (Bases greater than 16 are an extension.)\nAssigning a value outside this range to IBASE will result in a value of\n2 or 36.  Input numbers may contain the characters 0-9 and A-Z. (Note:\nThey must be capitals.  Lower case letters are variable names.)  Single\ndigit numbers always have the value of the digit regardless of the value\nof IBASE.  (i.e.  A = 10.)  For multi-digit numbers, 'bc' changes all\ninput digits greater or equal to IBASE to the value of IBASE-1.  This\nmakes the number 'ZZZ' always be the largest 3 digit number of the input\nbase.\n\nFull expressions are similar to many other high level languages.\nSince there is only one kind of number, there are no rules for mixing\ntypes.  Instead, there are rules on the scale of expressions.  Every\nexpression has a scale.  This is derived from the scale of original\nnumbers, the operation performed and in many cases, the value of the\nvariable SCALE.  Legal values of the variable SCALE are 0 to the maximum\nnumber representable by a C integer.\n\nFile: bc.info,  Node: Basic Expressions,  Next: Relational Expressions,  Prev: About Expressions and Special Variables,  Up: Expressions\n"
                    },
                    {
                        "name": "3.2 Basic Expressions",
                        "content": "In the following descriptions of legal expressions, \"expr\" refers to a\ncomplete expression and \"VAR\" refers to a simple or an array variable.\nA simple variable is just a\n\nNAME\n\nand an array variable is specified as\n\nNAME[EXPR]\n\nUnless specifically mentioned the scale of the result is the maximum\nscale of the expressions involved.\n\n'- expr'\nThe result is the negation of the expression.\n\n'++ VAR'\nThe variable is incremented by one and the new value is the result\nof the expression.\n\n'-- VAR'\nThe variable is decremented by one and the new value is the result\nof the expression.\n\n'VAR ++'\nThe result of the expression is the value of the variable and then\nthe variable is incremented by one.\n\n'VAR --'\nThe result of the expression is the value of the variable and then\nthe variable is decremented by one.\n\n'expr + expr'\nThe result of the expression is the sum of the two expressions.\n\n'expr - expr'\nThe result of the expression is the difference of the two\nexpressions.\n\n'expr * expr'\nThe result of the expression is the product of the two expressions.\n\n'expr / expr'\nThe result of the expression is the quotient of the two\nexpressions.  The scale of the result is the value of the variable\n'scale'\n\n'expr % expr'\nThe result of the expression is the \"remainder\" and it is computed\nin the following way.  To compute a%b, first a/b is computed to\nSCALE digits.  That result is used to compute a-(a/b)*b to the\nscale of the maximum of SCALE+scale(b) and scale(a).  If SCALE is\nset to zero and both expressions are integers this expression is\nthe integer remainder function.\n\n'expr ^ expr'\nThe result of the expression is the value of the first raised to\nthe second.  The second expression must be an integer.  (If the\nsecond expression is not an integer, a warning is generated and the\nexpression is truncated to get an integer value.)  The scale of the\nresult is SCALE if the exponent is negative.  If the exponent is\npositive the scale of the result is the minimum of the scale of the\nfirst expression times the value of the exponent and the maximum of\nSCALE and the scale of the first expression.  (e.g.  scale(a^b) =\nmin(scale(a)*b, max(SCALE, scale(a))).)  It should be noted that\nexpr^0 will always return the value of 1.\n\n'( expr )'\nThis alters the standard precedence to force the evaluation of the\nexpression.\n\n'VAR = expr'\nThe variable is assigned the value of the expression.\n\n'VAR <op>= expr'\nThis is equivalent to \"VAR = VAR <op> expr\" with the exception that\nthe \"VAR\" part is evaluated only once.  This can make a difference\nif \"VAR\" is an array.\n\nFile: bc.info,  Node: Relational Expressions,  Next: Boolean Expressions,  Prev: Basic Expressions,  Up: Expressions\n"
                    },
                    {
                        "name": "3.3 Relational Expressions",
                        "content": "Relational expressions are a special kind of expression that always\nevaluate to 0 or 1, 0 if the relation is false and 1 if the relation is\ntrue.  These may appear in any legal expression.  (POSIX 'bc' requires\nthat relational expressions are used only in 'if', 'while', and 'for'\nstatements and that only one relational test may be done in them.)  The\nrelational operators are\n\n'expr1 < expr2'\nThe result is 1 if expr1 is strictly less than expr2.\n\n'expr1 <= expr2'\nThe result is 1 if expr1 is less than or equal to expr2.\n\n'expr1 > expr2'\nThe result is 1 if expr1 is strictly greater than expr2.\n\n'expr1 >= expr2'\nThe result is 1 if expr1 is greater than or equal to expr2.\n\n'expr1 == expr2'\nThe result is 1 if expr1 is equal to expr2.\n\n'expr1 != expr2'\nThe result is 1 if expr1 is not equal to expr2.\n\nFile: bc.info,  Node: Boolean Expressions,  Next: Precedence,  Prev: Relational Expressions,  Up: Expressions\n"
                    },
                    {
                        "name": "3.4 Boolean Expressions",
                        "content": "Boolean operations are also legal.  (POSIX 'bc' does NOT have boolean\noperations).  The result of all boolean operations are 0 and 1 (for\nfalse and true) as in relational expressions.  The boolean operators\nare:\n\n'!expr'\nThe result is 1 if expr is 0.\n\n'expr && expr'\nThe result is 1 if both expressions are non-zero.\n\n'expr || expr'\nThe result is 1 if either expression is non-zero.\n\nFile: bc.info,  Node: Precedence,  Next: Special Expressions,  Prev: Boolean Expressions,  Up: Expressions\n"
                    },
                    {
                        "name": "3.5 Precedence",
                        "content": "The expression precedence is as follows: (lowest to highest)\n\n|| operator, left associative\n&& operator, left associative\n! operator, nonassociative\nRelational operators, left associative\nAssignment operator, right associative\n+ and - operators, left associative\n*, / and % operators, left associative\n^ operator, right associative\nunary - operator, nonassociative\n++ and -- operators, nonassociative\n\nThis precedence was chosen so that POSIX compliant 'bc' programs will\nrun correctly.  This will cause the use of the relational and logical\noperators to have some unusual behavior when used with assignment\nexpressions.  Consider the expression:\n\na = 3 < 5\n\nMost C programmers would assume this would assign the result of \"3 <\n5\" (the value 1) to the variable \"a\".  What this does in 'bc' is assign\nthe value 3 to the variable \"a\" and then compare 3 to 5.  It is best to\nuse parentheses when using relational and logical operators with the\nassignment operators.\n\nFile: bc.info,  Node: Special Expressions,  Prev: Precedence,  Up: Expressions\n"
                    },
                    {
                        "name": "3.6 Special Expressions",
                        "content": "There are a few more special expressions that are provided in 'bc'.\nThese have to do with user-defined functions and standard functions.\nThey all appear as \"NAME'('PARAMETERS')'\".  *Note Functions::, for\nuser-defined functions.  The standard functions are:\n\n'length ( EXPRESSION )'\nThe value of the length function is the number of significant\ndigits in the expression.\n\n'read ( )'\nThe 'read' function (an extension) will read a number from the\nstandard input, regardless of where the function occurs.  Beware,\nthis can cause problems with the mixing of data and program in the\nstandard input.  The best use for this function is in a previously\nwritten program that needs input from the user, but never allows\nprogram code to be input from the user.  The value of the 'read'\nfunction is the number read from the standard input using the\ncurrent value of the variable IBASE for the conversion base.\n\n'scale ( EXPRESSION )'\nThe value of the 'scale' function is the number of digits after the\ndecimal point in the expression.\n\n'sqrt ( EXPRESSION )'\nThe value of the 'sqrt' function is the square root of the\nexpression.  If the expression is negative, a run time error is\ngenerated.\n\nFile: bc.info,  Node: Statements,  Next: Functions,  Prev: Expressions,  Up: Top\n"
                    }
                ]
            },
            "4 Statements": {
                "content": "* Menu:\n\n* Pseudo Statements::\n\nStatements (as in most algebraic languages) provide the sequencing of\nexpression evaluation.  In 'bc' statements are executed \"as soon as\npossible.\"  Execution happens when a newline in encountered and there is\none or more complete statements.  Due to this immediate execution,\nnewlines are very important in 'bc'.  In fact, both a semicolon and a\nnewline are used as statement separators.  An improperly placed newline\nwill cause a syntax error.  Because newlines are statement separators,\nit is possible to hide a newline by using the backslash character.  The\nsequence \"\\<nl>\", where <nl> is the newline appears to 'bc' as\nwhitespace instead of a newline.  A statement list is a series of\nstatements separated by semicolons and newlines.  The following is a\nlist of 'bc' statements and what they do: (Things enclosed in brackets (\n[ ] ) are optional parts of the statement.)\n\n'EXPRESSION'\nThis statement does one of two things.  If the expression starts\nwith \"<variable> <assignment> ...\", it is considered to be an\nassignment statement.  If the expression is not an assignment\nstatement, the expression is evaluated and printed to the output.\nAfter the number is printed, a newline is printed.  For example,\n\"a=1\" is an assignment statement and \"(a=1)\" is an expression that\nhas an embedded assignment.  All numbers that are printed are\nprinted in the base specified by the variable OBASE.  The legal\nvalues for OBASE are 2 through BCBASEMAX (*note Environment\nVariables::).  For bases 2 through 16, the usual method of writing\nnumbers is used.  For bases greater than 16, 'bc' uses a\nmulti-character digit method of printing the numbers where each\nhigher base digit is printed as a base 10 number.  The\nmulti-character digits are separated by spaces.  Each digit\ncontains the number of characters required to represent the base\nten value of \"OBASE -1\".  Since numbers are of arbitrary precision,\nsome numbers may not be printable on a single output line.  These\nlong numbers will be split across lines using the \"\\\" as the last\ncharacter on a line.  The maximum number of characters printed per\nline is 70.  Due to the interactive nature of 'bc', printing a\nnumber causes the side effect of assigning the printed value to the\nspecial variable LAST.  This allows the user to recover the last\nvalue printed without having to retype the expression that printed\nthe number.  Assigning to LAST is legal and will overwrite the last\nprinted value with the assigned value.  The newly assigned value\nwill remain until the next number is printed or another value is\nassigned to LAST.  (Some installations may allow the use of a\nsingle period (.)  which is not part of a number as a short hand\nnotation for for LAST.)\n\n'STRING'\nThe string is printed to the output.  Strings start with a double\nquote character and contain all characters until the next double\nquote character.  All characters are taken literally, including any\nnewline.  No newline character is printed after the string.\n\n'print LIST'\nThe 'print' statement (an extension) provides another method of\noutput.  The LIST is a list of strings and expressions separated by\ncommas.  Each string or expression is printed in the order of the\nlist.  No terminating newline is printed.  Expressions are\nevaluated and their value is printed and assigned to the variable\n'last'.  Strings in the print statement are printed to the output\nand may contain special characters.  Special characters start with\nthe backslash character (\\e).  The special characters recognized by\n'bc' are \"a\" (alert or bell), \"b\" (backspace), \"f\" (form feed), \"n\"\n(newline), \"r\" (carriage return), \"q\" (double quote), \"t\" (tab),\nand \"\\e\" (backslash).  Any other character following the backslash\nwill be ignored.\n\n'{ STATEMENTLIST }'\nThis is the compound statement.  It allows multiple statements to\nbe grouped together for execution.\n\n'if ( EXPRESSION ) STATEMENT1 [else STATEMENT2]'\nThe if statement evaluates the expression and executes statement1\nor statement2 depending on the value of the expression.  If the\nexpression is non-zero, statement1 is executed.  If statement2 is\npresent and the value of the expression is 0, then statement2 is\nexecuted.  (The 'else' clause is an extension.)\n\n'while ( EXPRESSION ) STATEMENT'\nThe while statement will execute the statement while the expression\nis non-zero.  It evaluates the expression before each execution of\nthe statement.  Termination of the loop is caused by a zero\nexpression value or the execution of a 'break' statement.\n\n'for ( [EXPRESSION1] ; [EXPRESSION2] ; [EXPRESSION3] ) STATEMENT'\nThe 'for' statement controls repeated execution of the statement.\nEXPRESSION1 is evaluated before the loop.  EXPRESSION2 is evaluated\nbefore each execution of the statement.  If it is non-zero, the\nstatement is evaluated.  If it is zero, the loop is terminated.\nAfter each execution of the statement, EXPRESSION3 is evaluated\nbefore the reevaluation of expression2.  If EXPRESSION1 or\nEXPRESSION3 are missing, nothing is evaluated at the point they\nwould be evaluated.  If EXPRESSION2 is missing, it is the same as\nsubstituting the value 1 for EXPRESSION2.  (The optional\nexpressions are an extension.  POSIX 'bc' requires all three\nexpressions.)  The following is equivalent code for the 'for'\nstatement:\n\nexpression1;\nwhile (expression2) {\nstatement;\nexpression3;\n}\n\n'break'\nThis statement causes a forced exit of the most recent enclosing\n'while' statement or 'for' statement.\n\n'continue'\nThe 'continue' statement (an extension) causes the most recent\nenclosing 'for' statement to start the next iteration.\n\n'halt'\nThe 'halt' statement (an extension) is an executed statement that\ncauses the 'bc' processor to quit only when it is executed.  For\nexample, \"if (0 == 1) halt\" will not cause 'bc' to terminate\nbecause the 'halt' is not executed.\n\n'return'\nReturn the value 0 from a function.  (*Note Functions::.)\n\n'return ( EXPRESSION )'\nReturn the value of the expression from a function.  (*Note\nFunctions::.)  As an extension, the parenthesis are not required.\n\nFile: bc.info,  Node: Pseudo Statements,  Prev: Statements,  Up: Statements\n",
                "subsections": [
                    {
                        "name": "4.1 Pseudo Statements",
                        "content": "These statements are not statements in the traditional sense.  They are\nnot executed statements.  Their function is performed at \"compile\" time.\n\n'limits'\nPrint the local limits enforced by the local version of 'bc'.  This\nis an extension.\n\n'quit'\nWhen the 'quit' statement is read, the 'bc' processor is\nterminated, regardless of where the 'quit' statement is found.  For\nexample, \"if (0 == 1) quit\" will cause 'bc' to terminate.\n\n'warranty'\nPrint a longer warranty notice.  This is an extension.\n\nFile: bc.info,  Node: Functions,  Next: Examples,  Prev: Statements,  Up: Top\n"
                    }
                ]
            },
            "5 Functions": {
                "content": "* Menu:\n\n* Math Library Functions::\n\nFunctions provide a method of defining a computation that can be\nexecuted later.  Functions in 'bc' always compute a value and return it\nto the caller.  Function definitions are \"dynamic\" in the sense that a\nfunction is undefined until a definition is encountered in the input.\nThat definition is then used until another definition function for the\nsame name is encountered.  The new definition then replaces the older\ndefinition.  A function is defined as follows:\n\ndefine NAME ( PARAMETERS ) { NEWLINE\nAUTOLIST   STATEMENTLIST }\n\nA function call is just an expression of the form \"'name'\n'('PARAMETERS')'\".\n\nParameters are numbers or arrays (an extension).  In the function\ndefinition, zero or more parameters are defined by listing their names\nseparated by commas.  All parameters are call by value parameters.\nArrays are specified in the parameter definition by the notation \"NAME'[\n]'\".  In the function call, actual parameters are full expressions for\nnumber parameters.  The same notation is used for passing arrays as for\ndefining array parameters.  The named array is passed by value to the\nfunction.  Since function definitions are dynamic, parameter numbers and\ntypes are checked when a function is called.  Any mismatch in number or\ntypes of parameters will cause a runtime error.  A runtime error will\nalso occur for the call to an undefined function.\n\nThe AUTOLIST is an optional list of variables that are for \"local\"\nuse.  The syntax of the auto list (if present) is \"'auto' NAME, ...  ;\".\n(The semicolon is optional.)  Each NAME is the name of an auto variable.\nArrays may be specified by using the same notation as used in\nparameters.  These variables have their values pushed onto a stack at\nthe start of the function.  The variables are then initialized to zero\nand used throughout the execution of the function.  At function exit,\nthese variables are popped so that the original value (at the time of\nthe function call) of these variables are restored.  The parameters are\nreally auto variables that are initialized to a value provided in the\nfunction call.  Auto variables are different than traditional local\nvariables because if function A calls function B, B may access function\nA's auto variables by just using the same name, unless function B has\ncalled them auto variables.  Due to the fact that auto variables and\nparameters are pushed onto a stack, 'bc' supports recursive functions.\n\nThe function body is a list of 'bc' statements.  Again, statements\nare separated by semicolons or newlines.  Return statements cause the\ntermination of a function and the return of a value.  There are two\nversions of the return statement.  The first form, \"'return'\", returns\nthe value 0 to the calling expression.  The second form, \"'return' (\nEXPRESSION )\", computes the value of the expression and returns that\nvalue to the calling expression.  There is an implied \"'return' (0)\" at\nthe end of every function.  This allows a function to terminate and\nreturn 0 without an explicit 'return' statement.\n\nFunctions also change the usage of the variable IBASE.  All constants\nin the function body will be converted using the value of IBASE at the\ntime of the function call.  Changes of IBASE will be ignored during the\nexecution of the function except for the standard function 'read', which\nwill always use the current value of IBASE for conversion of numbers.\n\nSeveral extensions have been added to functions.  First, the format\nof the definition has been slightly relaxed.  The standard requires the\nopening brace be on the same line as the 'define' keyword and all other\nparts must be on following lines.  This version of 'bc' will allow any\nnumber of newlines before and after the opening brace of the function.\nFor example, the following definitions are legal.\n\ndefine d (n) { return (2*n); }\ndefine d (n)\n{ return (2*n); }\n\nFunctions may be defined as 'void'.  A void funtion returns no value\nand thus may not be used in any place that needs a value.  A void\nfunction does not produce any output when called by itself on an input\nline.  The key word 'void' is placed between the key word 'define' and\nthe function name.  For example, consider the following session.\n\ndefine py (y) { print \"--->\", y, \"<---\", \"\\n\"; }\ndefine void px (x) { print \"--->\", x, \"<---\", \"\\n\"; }\npy(1)\n--->1<---\n0\npx(1)\n--->1<---\n\nSince 'py' is not a void function, the call of 'py(1)' prints the\ndesired output and then prints a second line that is the value of the\nfunction.  Since the value of a function that is not given an explicit\nreturn statement is zero, the zero is printed.  For 'px(1)', no zero is\nprinted because the function is a void function.\n\nAlso, call by variable for arrays was added.  To declare a call by\nvariable array, the declaration of the array parameter in the function\ndefinition looks like \"'*'NAME'[]'\".  The call to the function remains\nthe same as call by value arrays.\n\nFile: bc.info,  Node: Math Library Functions,  Prev: Functions,  Up: Functions\n",
                "subsections": [
                    {
                        "name": "5.1 Math Library Functions",
                        "content": "If 'bc' is invoked with the '-l' option, a math library is preloaded and\nthe default SCALE is set to 20.  The math functions will calculate their\nresults to the scale set at the time of their call.  The math library\ndefines the following functions:\n\n's (X)'\nThe sine of X, X is in radians.\n\n'c (X)'\nThe cosine of X, X is in radians.\n\n'a (X)'\nThe arctangent of X, arctangent returns radians.\n\n'l (X)'\nThe natural logarithm of X.\n\n'e (X)'\nThe exponential function of raising E to the value X.\n\n'j (N, X)'\nThe Bessel function of integer order N of X.\n\nFile: bc.info,  Node: Examples,  Next: Readline and Libedit Options,  Prev: Functions,  Up: Top\n"
                    }
                ]
            },
            "6 Examples": {
                "content": "In /bin/sh, the following will assign the value of \"pi\" to the shell\nvariable PI.\n\npi=$(echo \"scale=10; 4*a(1)\" | bc -l)\n\n\nThe following is the definition of the exponential function used in\nthe math library.  This function is written in POSIX 'bc'.\n\n\nscale = 20\n\n/* Uses the fact that e^x = (e^(x/2))^2\nWhen x is small enough, we use the series:\ne^x = 1 + x + x^2/2! + x^3/3! + ...\n*/\n\ndefine e(x) {\nauto  a, d, e, f, i, m, v, z\n\n/* Check the sign of x. */\nif (x<0) {\nm = 1\nx = -x\n}\n\n/* Precondition x. */\nz = scale;\nscale = 4 + z + .44*x;\nwhile (x > 1) {\nf += 1;\nx /= 2;\n}\n\n/* Initialize the variables. */\nv = 1+x\na = x\nd = 1\n\nfor (i=2; 1; i++) {\ne = (a *= x) / (d *= i)\nif (e == 0) {\nif (f>0) while (f--)  v = v*v;\nscale = z\nif (m) return (1/v);\nreturn (v/1);\n}\nv += e\n}\n}\n\n\nThe following is code that uses the extended features of 'bc' to\nimplement a simple program for calculating checkbook balances.  This\nprogram is best kept in a file so that it can be used many times without\nhaving to retype it at every use.\n\n\nscale=2\nprint \"\\nCheck book program\\n!\"\nprint \"  Remember, deposits are negative transactions.\\n\"\nprint \"  Exit by a 0 transaction.\\n\\n\"\n\nprint \"Initial balance? \"; bal = read()\nbal /= 1\nprint \"\\n\"\nwhile (1) {\n\"current balance = \"; bal\n\"transaction? \"; trans = read()\nif (trans == 0) break;\nbal -= trans\nbal /= 1\n}\nquit\n\n\nThe following is the definition of the recursive factorial function.\n\n\ndefine f (x) {\nif (x <= 1) return (1);\nreturn (f(x-1) * x);\n}\n\n\nFile: bc.info,  Node: Readline and Libedit Options,  Next: Comparison with Other Implementations,  Prev: Examples,  Up: Top\n",
                "subsections": []
            },
            "7 Readline and Libedit Options": {
                "content": "GNU 'bc' can be compiled (via a configure option) to use the GNU\n'readline' input editor library or the BSD 'libedit' library.  This\nallows the user to do more editing of lines before sending them to 'bc'.\nIt also allows for a history of previous lines typed.  When this option\nis selected, 'bc' has one more special variable.  This special variable,\nHISTORY is the number of lines of history retained.  A value of -1 means\nthat an unlimited number of history lines are retained.  This is the\ndefault value.  Setting the value of HISTORY to a positive number\nrestricts the number of history lines to the number given.  The value of\n0 disables the history feature.  For more information, read the user\nmanuals for the GNU 'readline', 'history' and BSD 'libedit' libraries.\nOne can not enable both 'readline' and 'libedit' at the same time.\n\nFile: bc.info,  Node: Comparison with Other Implementations,  Next: Limits,  Prev: Readline and Libedit Options,  Up: Top\n",
                "subsections": []
            },
            "8 Comparison with Other Implementations": {
                "content": "This version of 'bc' was implemented from the POSIX P1003.2/D11 draft\nand contains several differences and extensions relative to the draft\nand traditional implementations.  It is not implemented in the\ntraditional way using 'dc'.  This version is a single process which\nparses and runs a byte code translation of the program.  There is an\n\"undocumented\" option (-c) that causes the program to output the byte\ncode to the standard output instead of running it.  It was mainly used\nfor debugging the parser and preparing the math library.\n\nA major source of differences is extensions, where a feature is\nextended to add more functionality and additions, where new features are\nadded.  The following is the list of differences and extensions.\n\nLANG environment\nThis version does not conform to the POSIX standard in the\nprocessing of the LANG environment variable and all environment\nvariables starting with LC.\n\nnames\nTraditional and POSIX 'bc' have single letter names for functions,\nvariables and arrays.  They have been extended to be\nmulti-character names that start with a letter and may contain\nletters, numbers and the underscore character.\n\nStrings\nStrings are not allowed to contain NUL characters.  POSIX says all\ncharacters must be included in strings.\n\nlast\nPOSIX 'bc' does not have a \\fBlast variable.  Some implementations\nof 'bc' use the period (.)  in a similar way.\n\ncomparisons\nPOSIX 'bc' allows comparisons only in the 'if' statement, the\n'while' statement, and the second expression of the 'for'\nstatement.  Also, only one relational operation is allowed in each\nof those statements.\n\n'if' statement, 'else' clause\nPOSIX 'bc' does not have an 'else' clause.\n\n'for' statement\nPOSIX 'bc' requires all expressions to be present in the 'for'\nstatement.\n\n'&&,' '||', '!'\nPOSIX 'bc' does not have the logical operators.\n\n'read' function\nPOSIX 'bc' does not have a 'read' function.\n\n'print' statement\nPOSIX 'bc' does not have a 'print' statement.\n\n'continue' statement\nPOSIX 'bc' does not have a continue statement.\n\narray parameters\nPOSIX 'bc' does not (currently) support array parameters in full.\nThe POSIX grammar allows for arrays in function definitions, but\ndoes not provide a method to specify an array as an actual\nparameter.  (This is most likely an oversight in the grammar.)\nTraditional implementations of 'bc' have only call by value array\nparameters.\n\nfunction format\nPOSIX 'bc' requires the opening brace on the same line as the\n'define' key word and the 'auto' statement on the next line.\n\n'=+', '=-', '=*', '=/', '=%', '=^'\nPOSIX 'bc' does not require these \"old style\" assignment operators\nto be defined.  This version may allow these \"old style\"\nassignments.  Use the 'limits' statement to see if the installed\nversion supports them.  If it does support the \"old style\"\nassignment operators, the statement \"a =- 1\" will decrement 'a' by\n1 instead of setting 'a' to the value -1.\n\nspaces in numbers\nOther implementations of 'bc' allow spaces in numbers.  For\nexample, \"x=1 3\" would assign the value 13 to the variable x.  The\nsame statement would cause a syntax error in this version of 'bc'.\n\nerrors and execution\nThis implementation varies from other implementations in terms of\nwhat code will be executed when syntax and other errors are found\nin the program.  If a syntax error is found in a function\ndefinition, error recovery tries to find the beginning of a\nstatement and continue to parse the function.  Once a syntax error\nis found in the function, the function will not be callable and\nbecomes undefined.  Syntax errors in the interactive execution code\nwill invalidate the current execution block.  The execution block\nis terminated by an end of line that appears after a complete\nsequence of statements.  For example,\n\na = 1\nb = 2\n\nhas two execution blocks and\n\n{ a = 1\nb = 2 }\n\nhas one execution block.  Any runtime error will terminate the\nexecution of the current execution block.  A runtime warning will\nnot terminate the current execution block.\n\nInterrupts\nDuring an interactive session, the SIGINT signal (usually generated\nby the control-C character from the terminal) will cause execution\nof the current execution block to be interrupted.  It will display\na \"runtime\" error indicating which function was interrupted.  After\nall runtime structures have been cleaned up, a message will be\nprinted to notify the user that 'bc' is ready for more input.  All\npreviously defined functions remain defined and the value of all\nnon-auto variables are the value at the point of interruption.  All\nauto variables and function parameters are removed during the clean\nup process.  During a non-interactive session, the SIGINT signal\nwill terminate the entire run of 'bc'.\n\nFile: bc.info,  Node: Limits,  Next: Environment Variables,  Prev: Comparison with Other Implementations,  Up: Top\n",
                "subsections": []
            },
            "9 Limits": {
                "content": "The following are the limits currently in place for this 'bc' processor.\nSome of them may have been changed by an installation.  Use the 'limits'\nstatement to see the actual values.\n\n'BCBASEMAX'\nThe maximum output base is currently set at 999.  The maximum input\nbase is 16.\n\n'BCDIMMAX'\nThis is currently an arbitrary limit of 65535 as distributed.  Your\ninstallation may be different.\n\n'BCSCALEMAX'\nThe number of digits after the decimal point is limited to INTMAX\ndigits.  Also, the number of digits before the decimal point is\nlimited to INTMAX digits.\n\n'BCSTRINGMAX'\nThe limit on the number of characters in a string is INTMAX\ncharacters.\n\n'exponent'\nThe value of the exponent in the raise operation (^) is limited to\nLONGMAX.\n\n'multiply'\nThe multiply routine may yield incorrect results if a number has\nmore than LONGMAX / 90 total digits.  For 32 bit longs, this\nnumber is 23,860,929 digits.\n\n'variable names'\nThe current limit on the number of unique names is 32767 for each\nof simple variables, arrays and functions.\n\nFile: bc.info,  Node: Environment Variables,  Prev: Limits,  Up: Top\n",
                "subsections": []
            },
            "10 Environment Variables": {
                "content": "The following environment variables are processed by 'bc':\n\n'POSIXLYCORRECT'\nThis is the same as the -s option (*note Command Line Options::).\n\n'BCENVARGS'\nThis is another mechanism to get arguments to 'bc'.  The format is\nthe same as the command line arguments.  These arguments are\nprocessed first, so any files listed in the environment arguments\nare processed before any command line argument files.  This allows\nthe user to set up \"standard\" options and files to be processed at\nevery invocation of 'bc'.  The files in the environment variables\nwould typically contain function definitions for functions the user\nwants defined every time 'bc' is run.\n\n'BCLINELENGTH'\nThis should be an integer specifying the number of characters in an\noutput line for numbers.  This includes the backslash and newline\ncharacters for long numbers.  As an extension, the value of zero\ndisables the multi-line feature.  Any other value of this variable\nthat is less than 3 sets the line length to 70.\n\n",
                "subsections": []
            }
        }
    }
}