bcのヘルプ・マニュアル
日本語 英語
bc --help
usage: bc [options] [file ...]
-h --help print this usage and exit
-i --interactive force interactive mode
-l --mathlib use the predefined math routines
-q --quiet don't print initial banner
-s --standard non-standard bc constructs are errors
-w --warn warn about non-standard bc constructs
-v --version print version information and exit
usage: bc [options] [file ...]
-h --help print this usage and exit
-i --interactive force interactive mode
-l --mathlib use the predefined math routines
-q --quiet don't print initial banner
-s --standard non-standard bc constructs are errors
-w --warn warn about non-standard bc constructs
-v --version print version information and exit
man bc
bc(1) bc(1)
名称
bc - 任意精度の計算言語
書式
bc [ -hlwsqv ] [long-options] [ file ... ]
バージョン
このマニュアルは GNU bc version 1.06 について記述してあります。
解説
bc は、任意の精度の数値を扱う事ができ、プログラミング言語 C の文法によ
く似た形の入力を対話的に実行する言語です。コマンドラインのオプション の
指 定により、標準数学ライブラリを使用することもできます。これを指定した
場合は、どのファイルを処理するよりも前に数学ライブラリが定義されます 。
bc は動作を開始するとまず最初にコマンドラインで指定したファイルを順に処
理します。すべてのファイルを処理した後は、bc は標準入力からの読み込みを
行 います。すべてのコードは、それが読み込まれた時点で実行されていきます
。(もし、ファイル中にプロセッサを止めるコマンドが含まれていた場合は、標
準入力からの読み込みは行われません。)
本バージョンの bc は、伝統的な bc の実装および POSIX のドラフト規格より
も拡張されています。コマンドラインオプションにより、これらの拡張に対 し
て 警告を表示したり拒絶したりすることが可能です。本ドキュメントでは、こ
のプロセッサが受理する言語について説明します。拡張機能についてはその 旨
明記します。
オプション
-h, --help
使用方法を表示し、終了します。
-i, --interactive
対話モードを強制します。
-l, --mathlib
標準数学ライブラリを定義します。
-w, --warn
POSIX bc に対する拡張機能が入力された場合は警告を出します。
-s, --standard
POSIX bc の言語仕様に厳密に従って処理します。
-q, --quiet
GNU bc 導入メッセージを表示しません。
-v, --version
バージョン番号と著作権を表示して終了します。
数
bc における最も基本的な要素は ‘数’ です。数は、整数部と小数部があり、任
意の精度をとることができます。すべての数は、内部では 10 進数で表現さ れ
ており、計算も 10 進数で行われます。(本バージョンでは、除算と乗算で結果
に切捨てが起こります。) 数には length と scale という 2 つの属性があ り
ま す。 length は 10 進での有効桁数で、scale は小数点以下の 10 進での有
効桁数です。例えば、
.000001 は、lengthが 6 で、scale も 6 です。
1935.000 は、lengthが 7 で、scale が 3 です。
変数
数は、単純変数と配列の 2 種類の変数に保存されます。単純変数と配列変数に
は共に名前が付けられます。この名前は、最初の 1 文字目がアルファベットで
、後は、アルファベット、数字およびアンダスコアを任意の文字数組み合わ せ
て 使うことができます。すべてのアルファベットは小文字でなければなりませ
ん。 (アルファベットと数字を使った名前の機能は拡張機能です。 POSIX bc
では、変数に英小文字 1 文字しか許されません。) 配列変数の名前には必ずブ
ラケット ([]) がつくので、変数の型は文脈においてはっきりしています。
特殊な変数として scale, ibase, obase, last の 4 つの変数があり ま す 。
scale で計算時の小数点以下の有効桁数を指定します。 scale のデフォルトは
0 です。 ibase と obase で入力および出力の変換基数を指定します。デフ ォ
ル トでは、入力、出力の基数は共に 10 です。 last は、最後に bc が出力し
た数を保持しています (これは拡張機能です)。これらについては、後で適切な
と ころで詳しく説明します。これらの変数には、式で使われる代入と同様の代
入を行うことが可能です。
コメント
bc は、/* から */ の間をコメントとして扱います。コメントはどこから始 ま
っ ていてもよく、1 文字の空白として扱われます。 (これにより、コメントは
その前後の入力アイテムを切り離します。たとえば、変数名の途中にコメン ト
を 置くことはできません。) コメントの中にはいくつ改行があってもかまいま
せん。
bc をスクリプトとしても使えるようにするため、1 行コメントが拡張機能とし
て追加されました。1 行コメントは # で始まり、次の改行まで有効です。その
改行文字自体はコメントの一部とはみなされず、普通に処理されます。
式
‘数’ は、式および文によって操作されます。この言語は対話的になるように設
計 されているため、文および式は可能な限り即座に実行されます。 "main" プ
ログラムといったものはなく、そのかわり、コードはそれに出くわした時点 で
実 行されます。 (後で述べる‘関数’は、それに出くわした時点で定義されます
。)
式の最も単純なものは、ただの定数です。bc は、入力された定数 を 、 変 数
ibase で指定される現在の基数を元に、内部的には 10 進表現の数に変換しま
す。(関数の場合には例外があります。) ibase には、2 から 16 までが使用で
きます。この範囲を越える値を ibase に代入しようとすると、 2 あるいは 16
を指定したことになります。数の入力には、0-9 および A-F の文字が利用でき
ま す。(注意: これは大文字でなければなりません。小文字は変数名です。) 1
桁の数は ibase の値に関係なくその値を持ちます (すなわち A=10)。複数桁の
数 の場合、bc は ibase 以上の値をもつすべての入力桁を ibase-1に変更しま
す。これにより、数 FFF は常に、その入力基数を使って 3 桁で表現可能な 最
大の値を表します。
す べての演算式が、他の多くの高級言語に似たものとなっています。数の型は
1 種類しかないため、型変換の規則はありません。そのかわり、式の有効桁 数
に 関する規則があります。すべての式に有効桁数があり、これはその被演算数
の有効桁数と施される演算、それに多くの場合、変数 scale から決定されます
。scale には、0 から C の整数で表現できる最大の値までが指定可能です。
以 下、bc で使用可能な演算子を説明します。なお、完全形の式を "expr"、単
純変数または配列変数を "var" と表記します。単純変数は単に
name
と表し、配列変数は
name[expr]
と表します。特に言及しない限り、結果の有効桁数は、注目している式の最 大
有効桁数になります。
- expr 結果はその式の符号を反転したものとなります。
++ var 変数を 1 だけインクリメントし、その新しい値が式の結果となります
。
-- var 変数を 1 だけデクリメントし、その新しい値が式の結果となります。
var ++ 式の結果はその変数の値となり、それからその変数を 1 だけインク リ
メントします。
var -- 式の結果はその変数の値となり、それからその変数を 1 だけデクリメ
ントします。
expr + expr
式の結果は 2 つの式の和となります。
expr - expr
式の結果は 2 つの式の差となります。
expr * expr
式の結果は 2 つの式の積となります。
expr / expr
式の結果は 2 つの式の商となります。結果の scale は変数 scale の
値となります。
expr % expr
結果は、以下のようにして求められる剰余です。a%b を求めるために、
まず a/b を scale の有効桁数で計算します。この 結 果 を 用 い て
、a-(a/b)*b を、 scale+scale(b) と scale(a) の大きい方の有効桁数
で計算します。もし scale に 0 がセットされ、両方の式が整数であれ
ば、整数の剰余が求められます。
expr ^ expr
式 の結果は、1 番目の式の値を 2 番目の回数だけ乗じたものになりま
す。 2 番目の式は、整数でなければなりません。 (2 番目の式が整 数
で ない場合は警告が表示され、整数に切り詰めた値が使用されます。)
結果の scale は、べき指数が負なら scale になります。べき指数が正
な ら、 "1 番目の式の scale とべき指数との積" および "scale と 1
番目の式の scale の大きい方" の う ち の 小 さ い 方 ( つ ま り
、scale(a^b) = min(scale(a)*b, max( scale, scale(a)))) となりま
す。 expr^0 は常に 1 を返します。
( expr )
標準の優先度を使わずに、この式の評価を優先します。
var = expr
式の値が変数に代入されます。
var = expr
"var" が一度しか評価されないこと以外は "var = var expr" と
同じです。 "var" が配列の場合は動作が違うことがあり得ます。
関 係演算は特殊な演算で、結果は常に 0 か 1 になります。関係が偽の時 0、
真の時 1 になります。関係演算は、演算式のどこでも使う事がで き ま す 。
(POSIX bcでは、関係演算は、if, while, for 文の中だけで、しかも 1 つの関
係式しか使用できません。) 関係演算子は以下の通り。
expr1 < expr2
expr1 が expr2 より小さい場合 1 になります。
expr1 <= expr2
expr1 が expr2 より小さいか等しい場合 1 になります。
expr1 > expr2
expr1 が expr2 より大きい場合 1 になります。
expr1 >= expr2
expr1 が expr2 より大きいか等しい場合 1 になります。
expr1 == expr2
expr1 と expr2 が等しい場合 1 になります。
expr1 != expr2
expr1 と expr2 が等しくない場合 1 になります。
論理演算も使えます。(POSIX bc には論理演算はありません。) 論理演算も 関
係演算と同様、結果は 0 か 1 (各々偽および真) になります。論理演算子は以
下の通り。
!expr expr が 0 なら 1 になります。
expr && expr
expr1 と expr2 が両方とも 0 でないなら、1 になります。
expr || expr
expr1 と expr2 のどちらか一方が 0 でないなら、1 になります。
各演算子の優先順位と結合規則は次の通りです。 (最初のものほど低く、後 に
いくほど高い優先順位で先に実行されます。)
|| (左から結合)
&& (左から結合)
! (結合せず)
関係演算 (左から結合)
代入演算 (右から結合)
+ - (左から結合)
* / % (左から結合)
^ (右から結合)
- (単項マイナス) (結合せず)
++ -- (結合せず)
この優先順位は、POSIX bc のプログラムがそのまま正しく動くように配慮して
決められています。このため、関係演算と論理演算を代入文と共に用いた場 合
、通常とは異なる振る舞いをします。次の例を考えてみましょう:
a = 3 < 5
C プログラマのほとんどは、 ‘‘3 < 5’’ の関係演算が実行された結果 (つまり
1) が変数 ‘‘a’’ に代入される、と考えるでしょう。ところが bc では、ま ず
3 が変数 ‘‘a’’ に代入され、それから 3 と 5 の比較が行われるのです。この
間違いを避けるために、関係演算や論理演算を代入演算と共に用いる場合は 、
括弧を使うのが最良です。
bc には特別な式がさらにいくつか備わっています。それはユーザ定義関数と標
準関数に関するもので、すべて "name(parameters)" という形をしています 。
ユ ーザ定義関数については関数の章を参照して下さい。標準関数は以下の通り
です:
length ( expression )
expression の有効桁数を返します。
read ( )
(拡張機能) 関数の出現位置に関係なく、標準入力から数を読み取り ま
す。データとプログラムの両方を標準入力から与えるような場合には、
問題を生じうることに注意して下さい。最良の方法は、ユーザからデー
タの入力の必要があるなら、プログラムはあらかじめ作っておき、標準
入力からプログラムを入力しないようにすることです。 read 関数の値
は標準入力から読み込んだ数です。その際、変換基数として変数 ibase
の現在の値が用いられます。
scale ( expression )
expression の小数点以下の有効桁数を返します。
sqrt ( expression )
expression の平方根を返します。 expression に負の値を指定した 場
合は、ランタイムエラーになります。
文
文は (ほとんどの算術言語がそうであるように)、処理を順番に実行していく単
位です。 bc では文は「できるだけ早い段階で」実行されます。改行が入力 さ
れた時点で、実行可能な文が存在していれば、即座に実行します。このため bc
では改行が重要な役割を持っています。実際、セミコロンと改行が文の区切 り
と して使用されます。不適当な場所で改行を入力すると、文法エラーになりま
す。改行は文の区切りですが、バックスラッシュを用いて改行を隠すことが で
きます。 bc にとって、"\" (は改行) は改行ではなく空白に見えます
。文のリストは、セミコロンと改行で区切られた文の並びです。以下、bc の文
の 種類とその動作について説明します。 (なお、以下の説明で ([]) で括った
部分は省略可能な項です。)
演算式 演算式には次の 2 つの種類がありま す 。 演 算 式 が "
..." で始まっていれば、それは代入文として扱われます
。そうでなければ、演算式は評価されて出力に表示されます。結果が表
示 さ れた後、改行が表示されます。例えば、"a=1" は代入文であり、
"(a=1)" は代入文が埋め込まれた演算式です。表示される数値はすべて
、変数 obase で決まる基数で表示されます。 obase に指定できる値は
2 から BC_BASE_MAX までです。 (「制限」の章を参照。) 基数 2 から
16 まででは、通常の数表記法が用いられます。基数が 16 より大きい
場合、bc は、各桁を 10 進表記する複数桁文字表記法で表示します 。
複数桁文字表記法では、各桁は空白で区切られます。各桁は "obase-1"
を 10 進で表記するのに必要な桁数の数字から成ります。数の精度は任
意 に選べるため、数によっては 1 行に表示できない場合もあります。
そのような長い数は、行末に "\" を付けて次行に継続します。 1 行に
表示できる文字数は 70 です。 bc の対話的性質により、ある数を表示
すると、表示した値が特殊変数 last に代入されるという副作用が生じ
ます。ユーザはタイプし直すことなく最後に表示された値を再利用でき
ます。 last に値を代入することも可能で、その場合、前回表示された
値が代入値で上書きされます。新しく代入した値は、次に数が表示され
るか別の値が last に代入されるまで有効です。(bc の実装によっては
、 数の一部になっていない単一のピリオド (.) を last の短縮表記と
して用いることができます。)
string 文字列 string が出力に表示されます。文字列は二重引用符で始まり、
次の二重引用符までのすべての文字を含みます。改行を含め、すべての
文字は文字通りに解釈されます。文字列の後に改行は出力されません。
print list
print 文 ( これは拡張機能です) は、もうひとつの出力方法です。
"list" はコンマで区切った文字列および演算式のリストであり、各 文
字列あるいは演算式がリストの順に表示されます。最後に改行は出力さ
れません。演算式は評価され、その値が表示されるととも に 、 変 数
last に代入されます。 print 文中の文字列は出力に表示されますが、
特殊文字を含めることができます。特殊文字はバックスラッシ ュ (\)
で始まります。 bc で使える特殊文字は、 "a" (ベル)、"b" (バックス
ペース)、 "f" (フォームフィード)、"n" (改行)、"r" (復帰)、"q" (
二 重引用符)、 "t" (タブ)、"\" (バックスラッシュ) です。これ以外
は無視されます。
{ statement_list }
複文です。複数の文を 1 つのグループにまとめて実行します。
if ( expression ) statement1 [else statement2]
if 文は演算式 expression を評価し、その値に応じて 文 statement1
ま たは文 statement2 を実行します。 expression の値が 0 でなけれ
ば statement1 が実行されます。 statement2 が存在 し 、expression
の 値が 0 ならば、statement2 が実行されます。 (else 節は拡張機能
です。)
while ( expression ) statement
while 文は expression が 0 でない間、繰り返し statement を実行し
ま す 。 statement の 実 行前に毎回 expression を評価します。
expression の値が 0 になるか、break 文を実行すると、ループが終了
します。
for ( [expression1] ; [expression2] ; [expression3] ) statement
for 文は statement の繰り返し実行を制御します。 expression1 はル
ープ実行の前に評価されます。 expression2 は statement の実行前に
毎 回 評価され、その値が 0 でなければ statement が実行されます。
expression2 の値が 0 になると、ループは終了します。各 statement
実行の後、再び expression2 が評価される前に expression3 が評価さ
れます。 expression1 あるいは expression3 が省略されていると、そ
こ で は 何 も 評価されません。 expression2 が省略されている場合
、expression2 が 1 であるのと同様に扱われます。 ( 各 expression
が 省略可能なのは拡張機能です。 POSIX bc では、3 つの expression
はどれも省略できません。) 以下は for 文と等価なコードです:
expression1;
while (expression2) {
statement;
expression3;
}
break それを含む最も内側の while もしくは for 文による繰り返しを強制的
に中断します。
continue
そ れ を 含 む 最も内側の for 文における次の繰り返しに進みます。
(continue 文は拡張機能です)
halt 実行されると bc プロセッサを終了させます(拡張機能)。例え ば "if
(0 == 1) halt" の場合は bc は終了しません。 halt 文が実行されな
いからです。
return 関数から戻ります。関数の結果は 0 になります。(関数の章を参照)
return ( expression )
関数から戻ります。関数の結果は expression になります。(関数の 章
を参照) 拡張機能ですが、括弧は必須ではありません。
疑似文
こ れらは今までの文とは動作が異なります。疑似文は実行文ではなく、「コン
パイル」時点で処理されます。
limits bc のローカルバージョンにより制限される限界値を表 示 し ま す 。
(limits は拡張機能です)
quit bc を終了します。どんな場所にあっても、quit 文は入力された時点で
実行されます。例えば、 "if (0 == 1) quit" という記述であって
も、bc は終了します。
warranty
保証に関する注意を長めに表示します。 (warranty は拡張機能です)
関数
関 数は、後で実行されるべき計算手順を定義する機能です。 bc の関数は常に
値を計算し、それを呼びだし側に返します。関数定義は、それが入力から読 み
込 まれた時点で定義が行われるという点で「ダイナミック(動的)」です。一度
定義された関数は、同じ名前で別の関数が定義されるまで使用可能で、新し い
関 数が定義された場合は、前の関数が置き換えられます。関数の定義は、以下
のように行います:
define name ( parameters ) { newline
auto_list statement_list }
関数呼び出しは、 "name(parameters)" という形式の演算式です。
パラメータ parameters は数あるいは配列 (拡張機能) です。関数定義では、0
あるいは 1 個以上のパラメータ名をコンマで区切って並べることで定義します
。数は値渡し(call by value)でのみ渡され、 配 列 は 変 数 渡 し(call by
variable)でのみ渡されます。配列はパラメータ定義中で "name[]" のように表
記して指定します。関数呼び出しでは、数のパラメータに対して完全な演算 式
の 実パラメータを記述します。配列を渡す表記は配列パラメータ定義と同様で
す。名前付き配列は変数(variable)によって関数に渡されます。関数定義は ダ
イ ナミックゆえ、パラメータの数と型は関数呼び出しの際にチェックされます
。パラメータの数あるいは型に何らかの不整合があると、ランタイムエラー が
発生します。未定義関数を呼び出した場合もランタイムエラーとなります。
auto_list は 省 略 可能で、ローカル変数として使用する変数のリストです
。auto_list が存在するなら、その文法は "auto name, ... ;" となります。(
セ ミコロンは省略可能です。) 各 name がローカル変数の名前となります。配
列はパラメータと同様の表記で指定できます。これらの変数は、関数の最初 で
その値がスタックにプッシュされたのち値 0 に初期化され、関数の実行中に使
用されます。これらの変数は関数出口にてポップされ、 (関数呼び出し時の)元
の 値が復元されます。パラメータは実際にはローカル変数であり、関数呼び出
しで与えられた値に初期化されます。 bc のローカル変数は伝統的な意味で の
ロ ーカル変数と異なり、関数 A が関数 B を呼び出しているような場合、関数
B の中に関数 A のローカル変数と同じ名前のローカル変数がない限り、関数 A
の ローカル変数名をそのまま使って、関数 B から関数 A のローカル変数をア
クセスできます。ローカル変数とパラメータはスタックにプッシュされるた め
、 bc は再帰的な関数呼び出しをサポートしています。
関 数本体は bc の文のリストです。繰り返し述べますと、文はセミコロンか改
行で区切られています。 return 文により関数は終了し、値を 返 し ま す 。
return 文には 2 つの形式があり、ひとつめの形式 "return" は、呼び出し元
に値 0 を返します。もうひとつの形式 "return ( expression )" は 、
expression の値を計算し、それを呼び出し元に返します。各関数の最後には
"return (0)" があるものと解釈されます。これにより、明示的に return 文を
置かなくても、関数は終了して値 0 を返します。
関数の中では、変数 ibase の動作が変わります。関数の中で使われている定数
は、関数の呼びだし時点の ibase を元に変換が行われます。このため、関数内
部で ibase を変更しても無視されます。ただし、標準関数 read を呼び出した
場合は例外で、これは常に現在の ibase の値をもとに変換が行われます。
拡張機能ですが、定義の書式が若干緩やかになりました。標準では、開くブ レ
ー スが define キーワードと同じ行にあることと、他の部分が引き続く行にあ
ることが必須です。本バージョンの bc では、関数の開くブレースの前後の 改
行数は任意です。例えば、次の定義は合法です。
define d (n) { return (2*n); }
define d (n)
{ return (2*n); }
数学ライブラリ
bc に -l オプションを付けて起動した場合は、数学ライブラリが読み込まれ、
デフォルトの scale が 20 に設定されます。数学関数は、それを呼び出した時
点の scale の値に従って計算を行います。数学ライブラリによって使用可能に
なる関数は、次の通りです:
s (x) sin (x の単位はラジアン)
c (x) cos (x の単位はラジアン)
a (x) atan (返り値の単位はラジアン)
l (x) log (自然対数)
e (x) exp (指数関数)
j (n,x)
整数 n 次のベッセル関数
使用例
次の例は、/bin/sh でシェル変数 pi に ‘‘パイ’’ の値を代入します。
pi=$(echo "scale=10; 4*a(1)" | bc -l)
次の例は、数学ライブラリで使われている ‘‘e (x)’’ の定義です。この関数は
POSIX bc で記述されています。
scale = 20
/* Uses the fact that e^x = (e^(x/2))^2
When x is small enough, we use the series:
e^x = 1 + x + x^2/2! + x^3/3! + ...
*/
define e(x) {
auto a, d, e, f, i, m, v, z
/* Check the sign of x. */
if (x<0) {
m = 1
x = -x
}
/* Precondition x. */
z = scale;
scale = 4 + z + .44*x;
while (x > 1) {
f += 1;
x /= 2;
}
/* Initialize the variables. */
v = 1+x
a = x
d = 1
for (i=2; 1; i++) {
e = (a *= x) / (d *= i)
if (e == 0) {
if (f>0) while (f--) v = v*v;
scale = z
if (m) return (1/v);
return (v/1);
}
v += e
}
}
次 の例は、bc の拡張機能を使って、‘‘checkbook balances’’ (小切手帳残高)
を計算する簡単なプログラムです。このプログラムをファイルにしておくと 、
毎回タイプしなおさずに何度も使うことができます。
scale=2
print "\nCheck book program!\n"
print " Remember, deposits are negative transactions.\n"
print " Exit by a 0 transaction.\n\n"
print "Initial balance? "; bal = read()
bal /= 1
print "\n"
while (1) {
"current balance = "; bal
"transaction? "; trans = read()
if (trans == 0) break;
bal -= trans
bal /= 1
}
quit
次の例は、再帰呼び出しにより階乗を計算する関数です。
define f (x) {
if (x <= 1) return (1);
return (f(x-1) * x);
}
readline と libedit のオプション
GNU bc は (configure のオプションによって) GNU readline 入力エディタラ
イブラリまたは BSD libedit ライブラリを使うようにコンパイルできます。こ
れは、bc に入力する前に、行の編集を可能にします。以前に入力した行のヒス
トリも利用可能になります。このオプションでコンパイルされた bc では、 さ
ら に 1 つの特殊な変数 history が追加され、ヒストリに保存される行の数を
指定します。 readline では、その値が -1 (デフォルト値)なら、ヒストリ 行
は 制限なく保存されます。正の数を指定すると、ヒストリ行がその数に制限さ
れます。 0 ならヒストリ機能が無効になります。デフォルト値は 100 です 。
詳 し くは、ユーザマニュアルの GNU readline と history ライブラリと BSD
libedit をご覧下さい。 readline と libedit の両方を同時に有効化できませ
ん。
相違点
このバージョンの bc は POSIX P1003.2/D11 ドラフトから実装されており、そ
のドラフトや以前の実装に比べていくつかの相違点や拡張点があります。伝 統
的に行われていたような dc(1) を用いた実装ではありません。このバージョン
は単一プロセスであり、プログラムをバイトコードに変換したものを解析し て
実 行します。「ドキュメントに記載されていない」オプション (-c) があり、
プログラムを実行する代わりに、それをバイトコードに変換した結果を標準 出
力 に出力します。これは主として、パーザのデバッグと数学ライブラリの準備
に用いられました。
主な相違点は拡張機能によるものです。機能を高めたり追加したりするため に
機 能が拡張されたり、新機能が追加されたりしています。相違点と拡張点のリ
ストを以下に示します。
LANG このバージョンは、環境変数 LANG および LC_ で始まるすべての環 境
変数の処理に関して POSIX 標準に準拠していません。
名前 伝統的な bc および POSIX bc は、関数、変数、配列の名前として単一
の文字を使います。このバージョンでは、先頭が文字で始まり、文字と
数 字とアンダースコアで構成される 2 文字以上の名前が使えるように
拡張されています。
文字列 文字列には NUL 文字を含むことはできません。 POSIX では、文字列に
はあらゆる文字を含めることができなければならない、としています。
last POSIX bc には変数 last はありません。 bc の実装によっては 、last
と同じ意味でピリオド (.) を用いるものがあります。
比較 POSIX bc では、比較は if 文、while 文、for 文の第 2 式の中でのみ
用いることができます。また、これらの文の中ではただ 1 つの関係 演
算しか使えません。
if 文, else 節
POSIX bc には else 節はありません。
for 文 POSIX bc では for 文の各演算式は省略できません。
&&, ||, !
POSIX bc には論理演算子はありません。
read 関数
POSIX bc には read 関数はありません。
print 文
POSIX bc には print 文はありません。
continue 文
POSIX bc には continue 文はありません。
return 文
POSIX bc では、return 文の周りに括弧が必要です。
配列パラメータ
POSIX bc では (現在のところ) 配列パラメータは完全には使えません
。 POSIX の文法では、関数定義では配列を使えますが、実際に呼び 出
す ときのパラメータに配列を指定することができません。(これはおそ
らく、文法上の見落としでしょう。) 伝統的な bc の実装では、配列パ
ラメータは値渡しのみでした。
function format
POSIX bc では、開くブレースが define キーワードと同じ行にあり、
auto 文が次の行にあることが必要です。
=+, =-, =*, =/, =%, =^
POSIX bc ではこれらの「旧式」の代入演算子を定義する必要はあり ま
せん。このバージョンではこれらの「旧式」代入演算子が使えるかも知
れません。 limits 文を使って、インストールしたバージョンがこれら
をサポートしているかどうか、確かめてみて下さい。もしそのバージョ
ンが「旧式」代入演算子をサポートしていれば、文 "a =- 1" は a に
値 -1 を代入する代わりに a を 1 減じます。
数字表記中の空白
他の bc 実装では、数字表記の中に空白を含めることが許されます。例
えば、"x=1 3" は変数 x に値 13 を代入します。このバージョンの bc
では、先の文は文法エラーになります。
エラーと実行
このバージョンの bc は、プログラムに文法上のエラーや他のエラーが
見つかった場合にどういうコードが実行されるか、という点で、他の実
装と異なっています。ある関数定義中で文法エラーが見つかると、エラ
ー回復機構は文の先頭を見つけて関数のパーズを続けようと努力します
。ひとたび関数の中で文法エラーが見つかると、その関数は呼び出せな
くなり、未定義状態となります。対話的実行コードで文法エラーがある
と、現在の実行ブロックが無効になります。実行ブロックとは、ひと続
きの完全な文のあとの行末までのことです。例えば、次のコード
a = 1
b = 2
には 2 つの実行ブロックがあり、
{ a = 1
b = 2 }
には 1 つの実行ブロックがあります。ランタイムエラーが発生すると、現在の
実 行ブロックの実行が終了します。ランタイムの警告が発生しても、現在の実
行ブロックは終了しません。
割り込み
対話セッションの間、SIGINT シグナル (通常、端末からの Control-C
入力で発生します) によって現在の実行ブロックの実行が中断され、ど
の関数が中断されたかを示す「ランタイム」エラーが表示されます。ラ
ン タ イムのデータ構造をすべてクリアした後メッセージが表示され、
bc は次の入力を受け付ける状態になったことを示します。これまで に
定義した関数はすべて定義されて残っており、ローカルでない変数の値
は割り込み発生時点の値のままになっています。ローカル変数と関数パ
ラメータはすべて、クリア処理によって消去されます。非対話セッショ
ンでは、SIGINT シグナルで bc の実行全体が終了します。
限界
以下の項目が現在の bc プロセッサの限界値となっています。このうちいく つ
か は、インストール時に変更できます。実際の値を得るには limits 文を使っ
て下さい。
BC_BASE_MAX
現在のところ、出力の基数の最大値は 999 に設定されています。入 力
側の基数の最大値は 16 です。
BC_DIM_MAX
現 在のところ 65535 として配布されていますが、インストールしたバ
ージョンでは異なっているかも知れません。
BC_SCALE_MAX
小数点以下の桁数は INT_MAX 桁に制限されています。また、小数点 よ
り上の桁数も INT_MAX 桁に制限されています。
BC_STRING_MAX
文字列中の文字数は INT_MAX 文字に制限されています。
指数 累乗演算 (^) の指数の値は LONG_MAX に制限されています。
変 数 名 単純変数、配列、関数各々について、一意に識別される名前は 32767
個に制限されています。
環境変数
bc は以下の環境変数を解釈します。
POSIXLY_CORRECT
-s オプションと同じです。
BC_ENV_ARGS
これは bc に引数を渡す別の方法で、コマンドライン引き数と同じ書式
です。この引数が最初に処理されるので、この環境変数で指定されたフ
ァイルはコマンドライン引数で指定されたファイルよりも先に処理され
ます。これにより、毎回 bc を呼び出すごとに処理する「標準の」オプ
ションやファイルを設定できます。この環境変数で指定するファイルに
は 、bc を走らせるたびに定義しておきたいような関数の定義を書いて
おくとよいでしょう。
BC_LINE_LENGTH
数字を出力するときの 1 行の文字数を整数で指定します。数字が長 過
ぎると、バックスラッシュと改行を含めた出力となります。
診断
コ マンドラインで指定したファイルがオープンできない場合、 bc はファイル
が利用できない旨を表示して終了します。また、コンパイル時あるいはラン タ
イ ムの診断メッセージもありますが、それらは自身で理解できるようになって
いるはずです。
バグ
エラーリカバリがまだうまくいっていません。
バグ報告は、 bug-bc@gnu.org に電子メールでお願いします。単語 ‘‘bc’’ を
‘‘Subject:’’ フィールドのどこかに入れておいてください。
作者
Philip A. Nelson
philnelson@acm.org
謝辞
実 装をテストする際に広範囲に手助けしてくれた Steve Sommars (Steve.Som-
mars@att.com) に感謝します。たくさんの素晴らしい意見をもらいました。 彼
のおかげでとてもよいものになりました。
. bc(1)
bc(1) bc(1)
NAME
bc - An arbitrary precision calculator language
SYNTAX
bc [ -hlwsqv ] [long-options] [ file ... ]
DESCRIPTION
bc is a language that supports arbitrary precision numbers with inter-
active execution of statements. There are some similarities in the
syntax to the C programming language. A standard math library is
available by command line option. If requested, the math library is
defined before processing any files. bc starts by processing code from
all the files listed on the command line in the order listed. After
all files have been processed, bc reads from the standard input. All
code is executed as it is read. (If a file contains a command to halt
the processor, bc will never read from the standard input.)
This version of bc contains several extensions beyond traditional bc
implementations and the POSIX draft standard. Command line options can
cause these extensions to print a warning or to be rejected. This doc-
ument describes the language accepted by this processor. Extensions
will be identified as such.
OPTIONS
-h, --help
Print the usage and exit.
-i, --interactive
Force interactive mode.
-l, --mathlib
Define the standard math library.
-w, --warn
Give warnings for extensions to POSIX bc.
-s, --standard
Process exactly the POSIX bc language.
-q, --quiet
Do not print the normal GNU bc welcome.
-v, --version
Print the version number and copyright and quit.
NUMBERS
The most basic element in bc is the number. Numbers are arbitrary pre-
cision numbers. This precision is both in the integer part and the
fractional part. All numbers are represented internally in decimal and
all computation is done in decimal. (This version truncates results
from divide and multiply operations.) There are two attributes of num-
bers, the length and the scale. The length is the total number of sig-
nificant decimal digits in a number and the scale is the total number
of decimal digits after the decimal point. For example:
.000001 has a length of 6 and scale of 6.
1935.000 has a length of 7 and a scale of 3.
VARIABLES
Numbers are stored in two types of variables, simple variables and
arrays. Both simple variables and array variables are named. Names
begin with a letter followed by any number of letters, digits and
underscores. All letters must be lower case. (Full alpha-numeric
names are an extension. In POSIX bc all names are a single lower case
letter.) The type of variable is clear by the context because all
array variable names will be followed by brackets ([]).
There are four special variables, scale, ibase, obase, and last. scale
defines how some operations use digits after the decimal point. The
default value of scale is 0. ibase and obase define the conversion base
for input and output numbers. The default for both input and output is
base 10. last (an extension) is a variable that has the value of the
last printed number. These will be discussed in further detail where
appropriate. All of these variables may have values assigned to them
as well as used in expressions.
COMMENTS
Comments in bc start with the characters /* and end with the characters
*/. Comments may start anywhere and appear as a single space in the
input. (This causes comments to delimit other input items. For exam-
ple, a comment can not be found in the middle of a variable name.)
Comments include any newlines (end of line) between the start and the
end of the comment.
To support the use of scripts for bc, a single line comment has been
added as an extension. A single line comment starts at a # character
and continues to the next end of the line. The end of line character
is not part of the comment and is processed normally.
EXPRESSIONS
The numbers are manipulated by expressions and statements. Since the
language was designed to be interactive, statements and expressions are
executed as soon as possible. There is no "main" program. Instead,
code is executed as it is encountered. (Functions, discussed in detail
later, are defined when encountered.)
A simple expression is just a constant. bc converts constants into
internal decimal numbers using the current input base, specified by the
variable ibase. (There is an exception in functions.) The legal values
of ibase are 2 through 16. Assigning a value outside this range to
ibase will result in a value of 2 or 16. Input numbers may contain the
characters 0-9 and A-F. (Note: They must be capitals. Lower case let-
ters are variable names.) Single digit numbers always have the value
of the digit regardless of the value of ibase. (i.e. A = 10.) For
multi-digit numbers, bc changes all input digits greater or equal to
ibase to the value of ibase-1. This makes the number FFF always be the
largest 3 digit number of the input base.
Full expressions are similar to many other high level languages. Since
there is only one kind of number, there are no rules for mixing types.
Instead, there are rules on the scale of expressions. Every expression
has a scale. This is derived from the scale of original numbers, the
operation performed and in many cases, the value of the variable scale.
Legal values of the variable scale are 0 to the maximum number repre-
sentable by a C integer.
In the following descriptions of legal expressions, "expr" refers to a
complete expression and "var" refers to a simple or an array variable.
A simple variable is just a
name
and an array variable is specified as
name[expr]
Unless specifically mentioned the scale of the result is the maximum
scale of the expressions involved.
- expr The result is the negation of the expression.
++ var The variable is incremented by one and the new value is the
result of the expression.
-- var The variable is decremented by one and the new value is the
result of the expression.
var ++ The result of the expression is the value of the variable and
then the variable is incremented by one.
var -- The result of the expression is the value of the variable and
then the variable is decremented by one.
expr + expr
The result of the expression is the sum of the two expressions.
expr - expr
The result of the expression is the difference of the two
expressions.
expr * expr
The result of the expression is the product of the two expres-
sions.
expr / expr
The result of the expression is the quotient of the two expres-
sions. The scale of the result is the value of the variable
scale.
expr % expr
The result of the expression is the "remainder" and it is com-
puted in the following way. To compute a%b, first a/b is com-
puted to scale digits. That result is used to compute a-(a/b)*b
to the scale of the maximum of scale+scale(b) and scale(a). If
scale is set to zero and both expressions are integers this
expression is the integer remainder function.
expr ^ expr
The result of the expression is the value of the first raised to
the second. The second expression must be an integer. (If the
second expression is not an integer, a warning is generated and
the expression is truncated to get an integer value.) The scale
of the result is scale if the exponent is negative. If the
exponent is positive the scale of the result is the minimum of
the scale of the first expression times the value of the expo-
nent and the maximum of scale and the scale of the first expres-
sion. (e.g. scale(a^b) = min(scale(a)*b, max( scale,
scale(a))).) It should be noted that expr^0 will always return
the value of 1.
( expr )
This alters the standard precedence to force the evaluation of
the expression.
var = expr
The variable is assigned the value of the expression.
var = expr
This is equivalent to "var = var expr" with the exception
that the "var" part is evaluated only once. This can make a
difference if "var" is an array.
Relational expressions are a special kind of expression that always
evaluate to 0 or 1, 0 if the relation is false and 1 if the relation is
true. These may appear in any legal expression. (POSIX bc requires
that relational expressions are used only in if, while, and for state-
ments and that only one relational test may be done in them.) The
relational operators are
expr1 < expr2
The result is 1 if expr1 is strictly less than expr2.
expr1 <= expr2
The result is 1 if expr1 is less than or equal to expr2.
expr1 > expr2
The result is 1 if expr1 is strictly greater than expr2.
expr1 >= expr2
The result is 1 if expr1 is greater than or equal to expr2.
expr1 == expr2
The result is 1 if expr1 is equal to expr2.
expr1 != expr2
The result is 1 if expr1 is not equal to expr2.
Boolean operations are also legal. (POSIX bc does NOT have boolean
operations). The result of all boolean operations are 0 and 1 (for
false and true) as in relational expressions. The boolean operators
are:
!expr The result is 1 if expr is 0.
expr && expr
The result is 1 if both expressions are non-zero.
expr || expr
The result is 1 if either expression is non-zero.
The expression precedence is as follows: (lowest to highest)
|| operator, left associative
&& operator, left associative
! operator, nonassociative
Relational operators, left associative
Assignment operator, right associative
+ and - operators, left associative
*, / and % operators, left associative
^ operator, right associative
unary - operator, nonassociative
++ and -- operators, nonassociative
This precedence was chosen so that POSIX compliant bc programs will run
correctly. This will cause the use of the relational and logical opera-
tors to have some unusual behavior when used with assignment expres-
sions. Consider the expression:
a = 3 < 5
Most C programmers would assume this would assign the result of "3 < 5"
(the value 1) to the variable "a". What this does in bc is assign the
value 3 to the variable "a" and then compare 3 to 5. It is best to use
parenthesis when using relational and logical operators with the
assignment operators.
There are a few more special expressions that are provided in bc.
These have to do with user defined functions and standard functions.
They all appear as "name(parameters)". See the section on functions
for user defined functions. The standard functions are:
length ( expression )
The value of the length function is the number of significant
digits in the expression.
read ( )
The read function (an extension) will read a number from the
standard input, regardless of where the function occurs.
Beware, this can cause problems with the mixing of data and pro-
gram in the standard input. The best use for this function is
in a previously written program that needs input from the user,
but never allows program code to be input from the user. The
value of the read function is the number read from the standard
input using the current value of the variable ibase for the con-
version base.
scale ( expression )
The value of the scale function is the number of digits after
the decimal point in the expression.
sqrt ( expression )
The value of the sqrt function is the square root of the expres-
sion. If the expression is negative, a run time error is gener-
ated.
STATEMENTS
Statements (as in most algebraic languages) provide the sequencing of
expression evaluation. In bc statements are executed "as soon as pos-
sible." Execution happens when a newline in encountered and there is
one or more complete statements. Due to this immediate execution, new-
lines are very important in bc. In fact, both a semicolon and a newline
are used as statement separators. An improperly placed newline will
cause a syntax error. Because newlines are statement separators, it is
possible to hide a newline by using the backslash character. The
sequence "\", where is the newline appears to bc as whitespace
instead of a newline. A statement list is a series of statements sepa-
rated by semicolons and newlines. The following is a list of bc state-
ments and what they do: (Things enclosed in brackets ([]) are optional
parts of the statement.)
expression
This statement does one of two things. If the expression starts
with " ...", it is considered to be an
assignment statement. If the expression is not an assignment
statement, the expression is evaluated and printed to the out-
put. After the number is printed, a newline is printed. For
example, "a=1" is an assignment statement and "(a=1)" is an
expression that has an embedded assignment. All numbers that
are printed are printed in the base specified by the variable
obase. The legal values for obase are 2 through BC_BASE_MAX.
(See the section LIMITS.) For bases 2 through 16, the usual
method of writing numbers is used. For bases greater than 16,
bc uses a multi-character digit method of printing the numbers
where each higher base digit is printed as a base 10 number.
The multi-character digits are separated by spaces. Each digit
contains the number of characters required to represent the base
ten value of "obase-1". Since numbers are of arbitrary preci-
sion, some numbers may not be printable on a single output line.
These long numbers will be split across lines using the "\" as
the last character on a line. The maximum number of characters
printed per line is 70. Due to the interactive nature of bc,
printing a number causes the side effect of assigning the
printed value to the special variable last. This allows the user
to recover the last value printed without having to retype the
expression that printed the number. Assigning to last is legal
and will overwrite the last printed value with the assigned
value. The newly assigned value will remain until the next num-
ber is printed or another value is assigned to last. (Some
installations may allow the use of a single period (.) which is
not part of a number as a short hand notation for for last.)
string The string is printed to the output. Strings start with a dou-
ble quote character and contain all characters until the next
double quote character. All characters are take literally,
including any newline. No newline character is printed after
the string.
print list
The print statement (an extension) provides another method of
output. The "list" is a list of strings and expressions sepa-
rated by commas. Each string or expression is printed in the
order of the list. No terminating newline is printed. Expres-
sions are evaluated and their value is printed and assigned to
the variable last. Strings in the print statement are printed to
the output and may contain special characters. Special charac-
ters start with the backslash character (\). The special char-
acters recognized by bc are "a" (alert or bell), "b"
(backspace), "f" (form feed), "n" (newline), "r" (carriage
return), "q" (double quote), "t" (tab), and "\" (backslash).
Any other character following the backslash will be ignored.
{ statement_list }
This is the compound statement. It allows multiple statements
to be grouped together for execution.
if ( expression ) statement1 [else statement2]
The if statement evaluates the expression and executes state-
ment1 or statement2 depending on the value of the expression.
If the expression is non-zero, statement1 is executed. If
statement2 is present and the value of the expression is 0, then
statement2 is executed. (The else clause is an extension.)
while ( expression ) statement
The while statement will execute the statement while the expres-
sion is non-zero. It evaluates the expression before each exe-
cution of the statement. Termination of the loop is caused by
a zero expression value or the execution of a break statement.
for ( [expression1] ; [expression2] ; [expression3] ) statement
The for statement controls repeated execution of the statement.
Expression1 is evaluated before the loop. Expression2 is evalu-
ated before each execution of the statement. If it is non-zero,
the statement is evaluated. If it is zero, the loop is termi-
nated. After each execution of the statement, expression3 is
evaluated before the reevaluation of expression2. If expres-
sion1 or expression3 are missing, nothing is evaluated at the
point they would be evaluated. If expression2 is missing, it is
the same as substituting the value 1 for expression2. (The
optional expressions are an extension. POSIX bc requires all
three expressions.) The following is equivalent code for the
for statement:
expression1;
while (expression2) {
statement;
expression3;
}
break This statement causes a forced exit of the most recent enclosing
while statement or for statement.
continue
The continue statement (an extension) causes the most recent
enclosing for statement to start the next iteration.
halt The halt statement (an extension) is an executed statement that
causes the bc processor to quit only when it is executed. For
example, "if (0 == 1) halt" will not cause bc to terminate
because the halt is not executed.
return Return the value 0 from a function. (See the section on func-
tions.)
return ( expression )
Return the value of the expression from a function. (See the
section on functions.) As an extension, the parenthesis are not
required.
PSEUDO STATEMENTS
These statements are not statements in the traditional sense. They are
not executed statements. Their function is performed at "compile"
time.
limits Print the local limits enforced by the local version of bc.
This is an extension.
quit When the quit statement is read, the bc processor is terminated,
regardless of where the quit statement is found. For example,
"if (0 == 1) quit" will cause bc to terminate.
warranty
Print a longer warranty notice. This is an extension.
FUNCTIONS
Functions provide a method of defining a computation that can be exe-
cuted later. Functions in bc always compute a value and return it to
the caller. Function definitions are "dynamic" in the sense that a
function is undefined until a definition is encountered in the input.
That definition is then used until another definition function for the
same name is encountered. The new definition then replaces the older
definition. A function is defined as follows:
define name ( parameters ) { newline
auto_list statement_list }
A function call is just an expression of the form "name(parameters)".
Parameters are numbers or arrays (an extension). In the function defi-
nition, zero or more parameters are defined by listing their names sep-
arated by commas. All parameters are call by value parameters. Arrays
are specified in the parameter definition by the notation "name[]".
In the function call, actual parameters are full expressions for number
parameters. The same notation is used for passing arrays as for defin-
ing array parameters. The named array is passed by value to the func-
tion. Since function definitions are dynamic, parameter numbers and
types are checked when a function is called. Any mismatch in number or
types of parameters will cause a runtime error. A runtime error will
also occur for the call to an undefined function.
The auto_list is an optional list of variables that are for "local"
use. The syntax of the auto list (if present) is "auto name, ... ;".
(The semicolon is optional.) Each name is the name of an auto vari-
able. Arrays may be specified by using the same notation as used in
parameters. These variables have their values pushed onto a stack at
the start of the function. The variables are then initialized to zero
and used throughout the execution of the function. At function exit,
these variables are popped so that the original value (at the time of
the function call) of these variables are restored. The parameters are
really auto variables that are initialized to a value provided in the
function call. Auto variables are different than traditional local
variables because if function A calls function B, B may access function
A’s auto variables by just using the same name, unless function B has
called them auto variables. Due to the fact that auto variables and
parameters are pushed onto a stack, bc supports recursive functions.
The function body is a list of bc statements. Again, statements are
separated by semicolons or newlines. Return statements cause the ter-
mination of a function and the return of a value. There are two ver-
sions of the return statement. The first form, "return", returns the
value 0 to the calling expression. The second form, "return ( expres-
sion )", computes the value of the expression and returns that value to
the calling expression. There is an implied "return (0)" at the end of
every function. This allows a function to terminate and return 0 with-
out an explicit return statement.
Functions also change the usage of the variable ibase. All constants
in the function body will be converted using the value of ibase at the
time of the function call. Changes of ibase will be ignored during the
execution of the function except for the standard function read, which
will always use the current value of ibase for conversion of numbers.
Several extensions have been added to functions. First, the format of
the definition has been slightly relaxed. The standard requires the
opening brace be on the same line as the define keyword and all other
parts must be on following lines. This version of bc will allow any
number of newlines before and after the opening brace of the function.
For example, the following definitions are legal.
define d (n) { return (2*n); }
define d (n)
{ return (2*n); }
Functions may be defined as void. A void funtion returns no value and
thus may not be used in any place that needs a value. A void function
does not produce any output when called by itself on an input line.
The key word void is placed between the key word define and the func-
tion name. For example, consider the following session.
define py (y) { print "--->", y, "<---", "0; }
define void px (x) { print "--->", x, "<---", "0; }
py(1)
--->1<---
0
px(1)
--->1<---
Since py is not a void function, the call of py(1) prints the desired
output and then prints a second line that is the value of the function.
Since the value of a function that is not given an explicit return
statement is zero, the zero is printed. For px(1), no zero is printed
because the function is a void function.
Also, call by variable for arrays was added. To declare a call by
variable array, the declaration of the array parameter in the function
definition looks like "*name[]". The call to the function remains the
same as call by value arrays.
MATH LIBRARY
If bc is invoked with the -l option, a math library is preloaded and
the default scale is set to 20. The math functions will calculate
their results to the scale set at the time of their call. The math
library defines the following functions:
s (x) The sine of x, x is in radians.
c (x) The cosine of x, x is in radians.
a (x) The arctangent of x, arctangent returns radians.
l (x) The natural logarithm of x.
e (x) The exponential function of raising e to the value x.
j (n,x)
The Bessel function of integer order n of x.
EXAMPLES
In /bin/sh, the following will assign the value of "pi" to the shell
variable pi.
pi=$(echo "scale=10; 4*a(1)" | bc -l)
The following is the definition of the exponential function used in the
math library. This function is written in POSIX bc.
scale = 20
/* Uses the fact that e^x = (e^(x/2))^2
When x is small enough, we use the series:
e^x = 1 + x + x^2/2! + x^3/3! + ...
*/
define e(x) {
auto a, d, e, f, i, m, v, z
/* Check the sign of x. */
if (x<0) {
m = 1
x = -x
}
/* Precondition x. */
z = scale;
scale = 4 + z + .44*x;
while (x > 1) {
f += 1;
x /= 2;
}
/* Initialize the variables. */
v = 1+x
a = x
d = 1
for (i=2; 1; i++) {
e = (a *= x) / (d *= i)
if (e == 0) {
if (f>0) while (f--) v = v*v;
scale = z
if (m) return (1/v);
return (v/1);
}
v += e
}
}
The following is code that uses the extended features of bc to imple-
ment a simple program for calculating checkbook balances. This program
is best kept in a file so that it can be used many times without having
to retype it at every use.
scale=2
print "\nCheck book program!\n"
print " Remember, deposits are negative transactions.\n"
print " Exit by a 0 transaction.\n\n"
print "Initial balance? "; bal = read()
bal /= 1
print "\n"
while (1) {
"current balance = "; bal
"transaction? "; trans = read()
if (trans == 0) break;
bal -= trans
bal /= 1
}
quit
The following is the definition of the recursive factorial function.
define f (x) {
if (x <= 1) return (1);
return (f(x-1) * x);
}
READLINE AND LIBEDIT OPTIONS
GNU bc can be compiled (via a configure option) to use the GNU readline
input editor library or the BSD libedit library. This allows the user
to do editing of lines before sending them to bc. It also allows for a
history of previous lines typed. When this option is selected, bc has
one more special variable. This special variable, history is the num-
ber of lines of history retained. For readline, a value of -1 means
that an unlimited number of history lines are retained. Setting the
value of history to a positive number restricts the number of history
lines to the number given. The value of 0 disables the history fea-
ture. The default value is 100. For more information, read the user
manuals for the GNU readline, history and BSD libedit libraries. One
can not enable both readline and libedit at the same time.
DIFFERENCES
This version of bc was implemented from the POSIX P1003.2/D11 draft and
contains several differences and extensions relative to the draft and
traditional implementations. It is not implemented in the traditional
way using dc(1). This version is a single process which parses and
runs a byte code translation of the program. There is an "undocu-
mented" option (-c) that causes the program to output the byte code to
the standard output instead of running it. It was mainly used for
debugging the parser and preparing the math library.
A major source of differences is extensions, where a feature is
extended to add more functionality and additions, where new features
are added. The following is the list of differences and extensions.
LANG environment
This version does not conform to the POSIX standard in the pro-
cessing of the LANG environment variable and all environment
variables starting with LC_.
names Traditional and POSIX bc have single letter names for functions,
variables and arrays. They have been extended to be multi-char-
acter names that start with a letter and may contain letters,
numbers and the underscore character.
Strings
Strings are not allowed to contain NUL characters. POSIX says
all characters must be included in strings.
last POSIX bc does not have a last variable. Some implementations of
bc use the period (.) in a similar way.
comparisons
POSIX bc allows comparisons only in the if statement, the while
statement, and the second expression of the for statement.
Also, only one relational operation is allowed in each of those
statements.
if statement, else clause
POSIX bc does not have an else clause.
for statement
POSIX bc requires all expressions to be present in the for
statement.
&&, ||, !
POSIX bc does not have the logical operators.
read function
POSIX bc does not have a read function.
print statement
POSIX bc does not have a print statement .
continue statement
POSIX bc does not have a continue statement.
return statement
POSIX bc requires parentheses around the return expression.
array parameters
POSIX bc does not (currently) support array parameters in full.
The POSIX grammar allows for arrays in function definitions, but
does not provide a method to specify an array as an actual
parameter. (This is most likely an oversight in the grammar.)
Traditional implementations of bc have only call by value array
parameters.
function format
POSIX bc requires the opening brace on the same line as the
define key word and the auto statement on the next line.
=+, =-, =*, =/, =%, =^
POSIX bc does not require these "old style" assignment operators
to be defined. This version may allow these "old style" assign-
ments. Use the limits statement to see if the installed version
supports them. If it does support the "old style" assignment
operators, the statement "a =- 1" will decrement a by 1 instead
of setting a to the value -1.
spaces in numbers
Other implementations of bc allow spaces in numbers. For exam-
ple, "x=1 3" would assign the value 13 to the variable x. The
same statement would cause a syntax error in this version of bc.
errors and execution
This implementation varies from other implementations in terms
of what code will be executed when syntax and other errors are
found in the program. If a syntax error is found in a function
definition, error recovery tries to find the beginning of a
statement and continue to parse the function. Once a syntax
error is found in the function, the function will not be
callable and becomes undefined. Syntax errors in the interac-
tive execution code will invalidate the current execution block.
The execution block is terminated by an end of line that appears
after a complete sequence of statements. For example,
a = 1
b = 2
has two execution blocks and
{ a = 1
b = 2 }
has one execution block. Any runtime error will terminate the execu-
tion of the current execution block. A runtime warning will not termi-
nate the current execution block.
Interrupts
During an interactive session, the SIGINT signal (usually gener-
ated by the control-C character from the terminal) will cause
execution of the current execution block to be interrupted. It
will display a "runtime" error indicating which function was
interrupted. After all runtime structures have been cleaned up,
a message will be printed to notify the user that bc is ready
for more input. All previously defined functions remain defined
and the value of all non-auto variables are the value at the
point of interruption. All auto variables and function parame-
ters are removed during the clean up process. During a non-
interactive session, the SIGINT signal will terminate the entire
run of bc.
LIMITS
The following are the limits currently in place for this bc processor.
Some of them may have been changed by an installation. Use the limits
statement to see the actual values.
BC_BASE_MAX
The maximum output base is currently set at 999. The maximum
input base is 16.
BC_DIM_MAX
This is currently an arbitrary limit of 65535 as distributed.
Your installation may be different.
BC_SCALE_MAX
The number of digits after the decimal point is limited to
INT_MAX digits. Also, the number of digits before the decimal
point is limited to INT_MAX digits.
BC_STRING_MAX
The limit on the number of characters in a string is INT_MAX
characters.
exponent
The value of the exponent in the raise operation (^) is limited
to LONG_MAX.
variable names
The current limit on the number of unique names is 32767 for
each of simple variables, arrays and functions.
ENVIRONMENT VARIABLES
The following environment variables are processed by bc:
POSIXLY_CORRECT
This is the same as the -s option.
BC_ENV_ARGS
This is another mechanism to get arguments to bc. The format is
the same as the command line arguments. These arguments are
processed first, so any files listed in the environment argu-
ments are processed before any command line argument files.
This allows the user to set up "standard" options and files to
be processed at every invocation of bc. The files in the envi-
ronment variables would typically contain function definitions
for functions the user wants defined every time bc is run.
BC_LINE_LENGTH
This should be an integer specifying the number of characters in
an output line for numbers. This includes the backslash and new-
line characters for long numbers. As an extension, the value of
zero disables the multi-line feature. Any other value of this
variable that is less than 3 sets the line length to 70.
DIAGNOSTICS
If any file on the command line can not be opened, bc will report that
the file is unavailable and terminate. Also, there are compile and run
time diagnostics that should be self-explanatory.
BUGS
Error recovery is not very good yet.
Email bug reports to bug-bc@gnu.org. Be sure to include the word
‘‘bc’’ somewhere in the ‘‘Subject:’’ field.
AUTHOR
Philip A. Nelson
philnelson@acm.org
ACKNOWLEDGEMENTS
The author would like to thank Steve Sommars (Steve.Sommars@att.com)
for his extensive help in testing the implementation. Many great sug-
gestions were given. This is a much better product due to his involve-
ment.
GNU Project 2006-06-11 bc(1)