BELL

TELEPHONE

LABORATORIESIN CO RPOR4TC0
THE

INFORMATIONCONIAINCO

TM!!
USC
OF
CMPLOVCCSOF
LASOnATORICS.
INCO*--A7CO.
FOR● uBLICATIONMCRCINIS

FOR=L?LL lELCPMONC
Nor
ANO

IS

COVER

SHEET

FOR

TECHNICAL

TITLE- Users’ Reference to B

CASE CHARGED-

39199

k’XLING CAS)j- 39199 -MEMORANDUM

MM-72-1271-1

DATE- January 7, 1972
11”

AUTHOR- K._Thompson
Ext 2394

k’lLiNG SUWJiKTS- Compilers
Languages
PDP-11

ABSTRACTb is a computer language intended for recursive s primarily nonnumeric applications typified by system programming.

B has asmall, unrestrictive syntax that is easy to compile.

Because of

the unusual freedom of expression and a rich set of operators, B
programs are often quite compact.
I’hismanual contains a concise definition of the language, sample
programs, and instructions for using the PDP-11 version of B.

Text - 27’pages
References

<

.
MM-72

DISTRISUTION(REFERGE!
13 Q9-31

COMPLETEMEMORANDUM

TO

FILE5

CORRESPONOENCI?

-HOOFFICIAL
FILE
COPV
IFORM
2-7770)- PLUSONE WHITECOPV FOR
EACH AOOITIONAL
FILINGCASE
REFERENCE
OATE
FILE
COPY
(FORM
E-1328)13

REFERENCECOPIESSUP

AHU, A V
AL MQu IST,4
L JR
N? IOAS, E J
ARt4FlRUST ER, MlSS
AVIRILL,R M JR

M E+BAKER,ti O
BARTLETT,HACIE S
MI. LLINGION,MISSH
BIPEN,
M17S IRWA d
BLEI!3EPG,
G J
BODNAR, J J
LN4ENUF1, P
J
t114UhN, G u
BRCU4N, W STANLEYBUCK* I D
CAhACJAY, RULIO HCAFTAN,J H
CHFN, STEPHEN
CLAY Tfl N,DP
CL INESMITH,
C
R
CLIHEN, HARVEVCIPP,IJAVIOHCORASICK,MISS
M J
CkUf4E, LARRY
L
01 5A LvO, J J
ljIMINIJ,
L d
UULILFY, t4RS F H
EL fNBA4s,
FRITs
ET RA, R H
FL FISCHEP,HE REIERTFIJOALE, JUSEPHV
FR4NK, r41ss
a J
Fi4/Ih Z, ST EP14FN H
FQASER,A G
GIJLOSTEIN,A JAY
GRANOLE,J A JRGRfJSSo ARTHUR
G
liAMkl ING, R w

J

KLEIN,MISS
R L
KOCII, GEURGEE
La CAVa, JOSEPHLA GGY, ll J
LA N71S, E H
LA RSEN, B O

N4MED

t3Y

MONTGOMERY.
U LNORGAN, i P-”” -MUGGLIN,M

SHEETONLVTOGRAHAMcRL
GRIFFITHt
W G
HALL, ANDREW O JR
14AL L,141LTON
S JR
HALL, W A
HAL1, M G
HARP!ON,4.E3N
O
HARU7A,K
HAuSE, A O
HAVES, JEREMIAMF
HAvuAROtG
P
HERsENHAN,
C B
HIG14T, S L

GNIWZ,R O
OLSZEUSKI,EOWAROOS SAUNA,.A
F JR
PfRITSKY,NARTIN
M
PE771T,MRS GEORGETTEPIERSON,
HAA40L0 L
PILLA,MICHAELA
PINSON,FLLI07N+PPIM,
R09ERTC

IFFLANOtFREDERICKlRv INE,M
M
JENSEN,P O
JOHNSON, STEPMENCAKENNEDV,R08ER?
KNOWI.70N*KENNETH
KNu@SEN,l)ONALO
E
K(N4PFNER,R
KORNEGAVORLKREIDER,DANIELM

TUTFL’44N,0AVIDM
UL*ERtR M
UN IONt R F
IAALSH, WIS MARTHAG
ME L)EMEYER, G H
ME XFL8LAT,
QICFlARDL
kil CHMAN, M T
MI LLSIJN, ALAN N JP
ktl LFE, RbEERT
M
ucllo,
wAL7ERId
YAM IN, MRS E f
21 NNERQAN,
L
ZISLIS,
PAUL M
100
NAMES

C

LAYTON, RICHARO
L
LESK, M E
LESK, MRS ANN 6
LIN,
SHEN
::’ OERER, GO TTFRIEOM R
LYSKLAMA,HE[NZMADOEN, MRS D M
M4LCOLM,J A
MATHEIIS,
MAX V
MC FOldEN, J4MES
R
MC9GNALL),HSMI LLER, ALAN H
MI LLER, S E
MITRA, O
MOLINELL[,
JOHP4 J
MORGAN, IIENNISJHO? PIS, ROBER7
NINKE,
wILL IAM H
NY STROM, HARRVCPA TEL, C
PEPLINSK1,41SS
C4Ri3LPET ERSON*TG
P(lLLAK,HENRYORI CHMAN, P L
RI TC141E,0ENN1S
M
R013EFTS, C S
QOSEhTHi
L, CHAF’LESW
SCHRYE14,19
L
SCHURTER,W
H
SNARE,RC
SOUTHERN,MISSMARTHAJST ILL FRMAN, R
STRINE,MISS
A M
STURf4AN, JLlEL N
TEPFY,N E
T1411MPSON, K
TILLL)TSON,L C
TROT TER, EONARO
T

KN

SHEET

ONLV

CC! RR ESPONOENCE
5 COPIES
PLuS
ONE
EACH
FILINGL

L

AIJTHuR

CUPY

TO

FILES

-HO

FOR

AODITIONALSUBJECT

127
12
13

I

Lu@w IG, J J
LuTZ, KENNETH
J
Mb LHCIL, R E JR
M4LLON,14
E
MA PA NZANO, JF
MA ZUREK, EDkiARO
F
Mc GUI GA N, FR4NCIS
+

COVER

IMOVQM 00UGLA$COVER

HA NKINS,R w
HA NSF N,MRS
G J
H$h AS YMl W,041SS
JON I
HOALST,
BLAINEC
HU17SilN, i+ ILL14M
H
10pQLIT],o o
JEtkKINS,MRS JIFNNIEKELLY,L J
KEKNIGHAN,
BRIAN
w

K

10

REHM, T C
RF INIG,H
RI DOLE BERGER,CO
R17ACC0,J E
ROPOSH, R C
SANDBURG,lRUIN
M
SC HAEVITZQALAN VSE ARS, U 1“
SHALSBOLT, O 81 CHA@0]1
SK VOER, MRS. CCIROTHEAElTAGUE,3ERKLEVATEGETHoFF,
R M
TR(IVER,14RS
MARGARETM+TUKEV,JWN
k

PATENTOIVIS1ON
IF MEMORANLNJM
HASPATENTSIGNIFICANCE

127
1673
3416
5222
8234
CUPLGPCOMFII?TE IIEMORANOUM

DIR
Olrt

AL CAL AY, OAVIOAFMSTRONG,00UGLAS
B
AR N07,1)ENNIS
L
BAnURA, OENNISC
BAUGH, C R
13 EHLER,MISS BONNIEL
BE YER, JEAN-OAV1O*B IT7Rl
Ch, NRS M E
BLINN,JAMES
C
BLY, JOSEPHA
BUCHS8A,UM,S J
BUS INGER,PA
CAMPBELL,STEPHENT
CA SPERS, MRS BARBARAF
ChAME!ERS,
J M
CHRIST,C W JR
CUTLER,C CHAPIN
CUTLER,V H JRIXUTSCW, OAV1O
N
l-f!Y, J C
F141EOFIAN, ARTI+URO
FRCIST, H BONNELL(X RSHO, ALLENGIBB,
KENNETHR
GIL LET TF, OEAN

VOLLARO,J R
kAGP!ER, BRuCEowAGNER, NRS MARTHd
P
hHIPPLE,JOMN HkRIGLFY,RANOALLOYOUNG S, EOH4R0
A
YOUNG OJAMESA
96 NAMESGLASS .11
GO OONAN,
GUOOMAN,DAVIOJMI CH4EL

L> CITEOAS

REFFRENCE

SOURCE-1271-I.

.

@Bell laboratories
SUBJECT: Users’ Reference to B - Case 39199-11

DATE: January 7, 1972
FROM: K._Thompson
MM-72-1 271-1

MEMORANDUM ——FOR FILE~oQ Introduction
B is a computer language directly descendant from BCPL [1,2].

B

1s running at Murray Hill on the DEC PDP-11 computer under theUNIX-11 time sharing system [3,4].

B is good for recursive,

non-numeric, machine independent applications, such as system andlanguage work.
B, compared to BCPL, is syntactically rich in expressions andsyntactically poor in statements.

A look at the examples in sec-..tion 9 of this document will give a flavor of the language.
B was designed and implemented by D. M. Ritchie and the author.
2.(J Syntax
The syntactic notation in this manual is basically BNF with thezollowing exceptions:
1 . The metacharacters< and > are removed.

Literals areunderlined to differentiate them from syntactic variables.
2. The metacharacter~ is removed.

Each syntactic alternativeis placed on a separate line.
3. The metacharacters{ and } denote syntactic grouping.

“;>

.

-2-

4. A syntactic group followed by numer~cal sub
scripts denote repetition of{Jm,m,m+l,000{..};

m,m+l,,...,nand super-

the group as follows:—.
\~.~ .——
Canonical -Synta~‘ihe syntax given in this section defines all the legal constructions in B without specifying the association rules.

These aregiven later along with the semantic description of each construction.
program ::={definition}O
definition::=

name {[ {constant}& ]}~ {ival {t ival}o]$ ;name ( {name {9 name}O}~ ) statement
ival ::=
constant
namestatement ::=auto name {constant}: {, name {constant}~}O ; statement-—
extrn name {, name}. ; statement-—
name : statementcase constant : statement-—{ {statement}. ]if ( rvalue ) statement {else statement}~—while ( rvalue ) statement-—.
switch rvalue statement

.

●

-3-

goto-rvalue ;-—return {( rvalue )}: ;—-{rvalue}~ ;rvalue ::=( rvalue )lvalueconstantlvalue assign rvalue
inc-dec lvalue.
lvalue inc-dec
unary rvalue& lvaluervalue binary rvalue
rvalue ? rvalue : rvalue
rvalue ( {rvalue {, rvalue}O }: )assign ::=={binary}:

inc-dec ::=++--.-unary ::=!

binary ::=
I
I

&
==
—-

,
.

,

-4-

!=
<
<=
>
>=
<<
—
>>
—
+

‘%
*

lvalue ::=name* rvaluervalue [ rvalue ]constant ::={digit},* {char}f’ ‘“ {char}O “
name ::=
alpha {alpha-digit}:alpha-digit

::=

alpha
digit
~.z ——..
Comments .—and Character .—Sets~:,-’,

#-5-

Comments are delimited as in PL/I by /* and */.
In general, B requires tokens to be separated by blanks, comments
or newlines, however the compiler infers separators surrounding
any of the characters (){][] ~;?: or surrounding any maximal sequence of the characters +-*/<>&~l.
The character set used in B is ANSCII.
The syntactic variable ‘alpha” is not defined.

It represents thecharacters A to Z, a to z, _, and backspace.
The syntactic variable “digit’ is not defined.

It represents theCharacters 0, l? 2S ..O 9.
The syntactic variable ‘char’ is not defined.

It is essentiallyany character in the set plus the escape character ‘*’ followedby another character to represent characters not easily
represented in the set.

The following escape sequences are

currently defined:
*O

*e
*(
*)
*t
**
*“
*“
*n

null
end-of-file
{
}
tab
*
‘
‘*
new line

All keywords in the language are only recognized In lower case.
Keywords are reserved.

3.0 Rvalues ——and Lvalues
--—

-6-

An rvalue $s a binary bit pattern of a fixed length.
PDP-11 it is 16 bits.

On theObjects are rvalues of different kinds

such as integers, labels, vectors and functions”. The actual kindof object represented is called the type of the rvalue.
A B expression can be evaluated to yield an rvalue, but its typeis undefined until the rvalue is used in scme context.

It iS

then assumed to represent an object of the required type.

For

example, in the following function call(b?f:g[i] )(1 ,x>l )The expression(b?f:g[i]) is evaluated to yield an rvalue whichis interpreted to be of type’ function.
fact functions is not checked.

Whether f hd

g[i] are in

Similarly, b ig assumed to be oftype truth value, x to be type integer etc.
There is no check to-insure thatthereare’”notype’mismatches.

Similarly, there are .no~wantedj or unwanted, type conversions.
,

An lvalue is a bit pattern representing a storage location containing an rvalue.

An lvalue is a type in B.

The unary operator* can be used to interpret an rvalue as an lvalue. Thus*X
tiakuates the expression x to yield an rvalue, which is theninterpreted as an lvalue.

If it is then used in an rvalue con-cext, the application of * yields the rvalue therein stored.
operator * can be thought of as indirection.
The unary operator & can be used to interpret an lvalue as anrvalue. Thus

.,

The

“--.,

.

.

-7-

&x

evaluates the expression x as an lvalue.
then yields the lvalue as an rvalue.

The application of &‘l’heoperator & can there-

fore ke thought of as the address function.
The names lvalue and rvalue come from the assignment statement
which requires an lvalue on the left and an rvalue on the right.
~.Q Expression .——Evaluation
Binding of ~pressions(lvalues and rvalues) is in the same orderas the sub-sections of this section except as noted.

‘IhUsex-pressions referred to as operands of ‘+’ (section 4,4) are expressions definedin sections 4.1 to 4.3.

The binding of opera-

tors at the same level (left to right, right to left) is specified in each sub-section.
4.1 Primaw--1,

Expressions

A name is an lvalue of one of three storage classes (automatic, external and internal).

2. A decimal constant is an rva lUe.

It consists ot a digit

between 1 and 9 followed by any numker of digits between O
and 9.

The value of the constant should not exceed the

maximum value that can be stored in an object.
3. An octal constant is the same as a decimal constant exceptthat it begins with a zero.
8.

It is then interpreted in base

Note that 09 (base 8) is legal and equal to 011.

4. A character constant is represented ky ‘ followed by one or
two characters(possibly escaped) followed ~another

‘.

,
.

-8-

It has an rvalue equal to the value of the characters
packed and right adjusted.

-’)

5. A string is any number of characters between “ characters.
The characters are packed into adjacent objects (lvalues
sequential) and terminated with the character ‘*e’.

Thervalue of the string is the lvalue of the object containing
the first character.

See section 8.0 for library functions

used to manipulate strings in a machine independent
fashion.
6. Any expression in () parentheses is a primary expression.
Parentheses are used to alter order of binding.
7. A vector is a primary expression followed by any expressionin [] brackets.

The two expressions are evaluated torvalues, added and the result is used as an lvalue.

The

primary expression can be thought of as a pointer to thebase of a vector, while the bracketed expression can bethought of as the offset in the vector.

Since E1[E2] is

identical to *(E1+E2), and addition is commutative, thebase of the vector and the offset in the vector can swap
positions.
8. A function is a primary expression followed by any numberof expressions in () parentheses separated by commas.

The

expressions In parentheses are evaluated (in an unspecified
order) to rvalues and assigned to the function’s parameters.

The primary expression is evaluated to an rvalue(assumed to be type function).
called.

The function is thenEach call is recursive at little cost in time or

.

.

-9-

space.

Primary expressions are bound left to right.
4.Z Unary Operators
1.

‘

The rvalue (or indirection) prefix unary operator * isdescribed in section 3.0.

Its operand is evaluated torvalue, and then used as an lvalue.

In this manner, ad-dress arithmetic may be performed.
2. The lvalue (or address) prefix unary operator & is also
described in section 3.0.

Note that &*x is identically x,

but *&x is only x if x

an lvalue.

is

3. The operand of the negate prefix umry
preted as an integer rvalue.

operator - is inter-

The result is an rvalue with

opposite sign.
4. The NOT prefix unary operator ! takes an integer rvalue
operand.

The result is zero if the operand is non-zero.

The result is one if the operand is zero.
5. The increment ++ and decrement -- unary operators may be
used either in prefix or postfix form.
quires an lvalue operand.

Either form re-

The rvalue stored in the lvalue

is either incremented or decremented by one.

The result isthe rvalue either before or after the operation depending
on postfix or prefix notation respectively.

Thus if x

currently contains the rvalue 5, then ++x and x++ bothchange x to 6.

The value of ++x is 6 while x++ is 5.

Similarly,

and

--x

x--

result 4, the latter 5.

store

4 in X.

The former has

rvalue.

-1o-Unazy operators are bound right to left.

Thus -lx++ is bound-(1(X++)).
~.~ Multiplicative Operators‘lhemultiplicative binary operators *, /, and %, expect rvalue
integer operands.
1.

The result is also an integer.

The operator * denotes multiplication.

2. The operator / denotes division.

The result is correct if

the first operand is divisible by the second.

If bothoperands are positive, the result is truncated toward zero.
Otherwise the rounding is undefined, but never greater thanone.
3. The operator % denotes modulo.
tive, the result is correct.

If both operands are posiIt is undefined otherwise.

The multiplicative operators bind left to right.
4.4
Additive Operators- -—The binary operators + and - are add and subtract.

The additive

operators bind left to right.
~.~ —-Shift O~erators—
Xhe binary operators << and >> are left and right shift respectively.

The left rvalue operand is taken as a bit pattern.

right operand is taken as an integer shift count.
the bit pattern shifted by the shift count.
tilled with zeros.

The result is

Vacated bits are

The result is undefined if the shift count isnegative or larger than an object length.
~ind left to right.

The

The shift operators

.

.

-11-

~.~ —.—
Relational .
O~erators
The relational operators < (less than), <= (less than or equalco), > (greater than), and >= (greater than or equal to) take
integer rvalue operands.

The result is one if the operands are

Ln the given relation to one another.

The result is zero other-

W1 se.
~.~ Euuality Operators
-—-—
‘i’ne
equality operators == (equal to) and 1= (not equal to) perrorm similarly to the relation operators.
4.8-The AND operator & takes operands as bit patterns.

The result isthe bit pattern that is the bit-wise AND of the operands.

The

AhJLloperator binds and evaluates left to right.
~.j ~) operator
The OR operator~ performs exactly as AND, but the result is theoit-wise inclusive OR of the operands.

The OR operator also

Dinds and evaluates left to right.
Conditional .
Expression-4.10— -.--———‘L’hreervalue expressions separated by ? and : form a conditional
expression.

The first expression

evaluated.

If the result is non-zero, the second expression isevaluated and the third ignored.

(to the left of the ?) is

If the value is zero, thesecond expression is ignored and the third is evaluated.

The

result is either the evaluation of the second or third expression.

.

...

-12-

Binding is right to left. Thus a?b:c?d:e is a?b:(c?d:e).
~.fi Assignment ODerators-— ‘l’hereare

assignment operators in B.

16

All have the form

lvalue op rvalue‘i’heassignment operator=

merelytne result in the lvalue.
= !=,

=<,

=<=,

=>,

Qinary operation=>=,

evaluates

the rvalue

and stores

The assignment operators =!, =&, ===,

=<<,

=>>,

=+,

=-,

=%,

=*,

and

=/

performa(see sections 4.3 to 4.9) between the rvalue

stored in the assignment’s lvalue and the assignment’s rvalue.
The result is then stored in the lvalue.
identical to x=x*1O.

The expression x=*1O is

Note that this is not x= *1O.

of an assignment is the rvalue.

The result

Assignments bind right to left,

thus x=y=O assigns zero to y, then x, and returns the rvalue
zero.
5.0 Statements-Statements define program execution.
by the computer in sequence.

Each statement is executed

There are, of course, statements toconditionally or unconditionallyalter normal sequencing.

3.1 COMDOUnd -—-—..
Statement--A sequence of statements in {] braces is syntactically a single
statement.

This mechanism is provided so that where a single

statement is expected, any number of statements can be placed.
~.~ Conditional -——-.—
Statement
A conditional statement has two forms. The first:
if(rval’ue) statement,

.

.

-13-

evaluates the rvalue andnon-zero.

executes statement, if the rvalue

If the rvalue is zero, Statementl is Skipped.

is

The

second form:
if(rvalue) statement , Qgg--

statement 2

is defined as follows in terms of the first form:~~(x=(rvalue))statement, ~(!x)

statement

2‘thus, only one of the two statements is executed, depending on
t-ht? value

Of rvake.

In the above example, x is not a real vari-able, but just a demonstration aid.
5.3 ——
While Statement-‘Thewhile statement has the form:
while(rvalue) statement
The execution is described in terms of the conditional and goto
statements as follows:
x: if(rvalue){ statement qoto x; ]Thus the statement is executed repeatedly while the rvalue is
non-zero.
3.4-

Again, x is a demonstration aid.

Switch -—.
Statement-—
The

The switch statement is the most complicated statement in B.
switch has the form:
switch rvalue statement

1

Virtually always, statement , above is a compouti statement.

Eachstatement in statement 1 may be preceded by a case as follows:case constant~I.)uringexecution, the rvalue is evaluated and compared to eachcase constant in undefined order.

If a case constant is equal to

.

-14-

the evaluatedrvalue, control is passed to the statement follow-

ing the case.

If the rvalue matches none of the cases,

T.

statement, is skipped.
~.~ Goto Statement‘the goto statement is as follows:.uSq rvalue ~‘l’hervalue is expected to be of type label.
passed to the corresponding label.

Control is thenGoto’s cannot be executed toLabels outside the currently executing function level.
S.Q Return Statement
The return statement is used in a function to return control tothe caller of a function.
~~n

The first form simply returns control.

~

The second form returns an rvalue for the execution of the function.
return I rvalue J &The caller of the function need not use the returned rvalue.
Rvalue -——.Statement-3.7- —Any rvalue followed by a semicolon is a statement.

The two mostcommon rvalue statements are assignment and function call.
2.E -—
NuI1 ——Statement
A semicolon is a null statement causing no execution.

It is usedmainly to carry a label after the last executable statement in acompound statement.
to a while statement.

It sometimes has use to supply a null body

“’””~

-15-

5.Q Declarations
Declarations in B specify storage class of variables.

Such de-clarations also, in some circumstances, specify initialization.
There are three storage classes in B.

Automatic storage is allo-cated for each function invocation.

External storage is allocat-

ed before execution and is available to.any and all functions.
Internal storage is local to a function and is available only tothat function, but is available to all invocations of that function.
~.1 External —Declaration..—Z
The external declaration has the form:
extrn name, ~ name2 ... &-—The external declaration specifies that each of the named variables is of the external storage class.

The declaration mustoccur before the first use of each of the variables.

Each of thevariables must also be externally defined.
Q.~ -Automatic
Declaration--—..
The automatic declaration also constitutes a definition:
auto name, {constant}! ~ nanle2 {constant]! ... A-—In absence of the constant, the automatic declaration defines thevariable to be of class automatic.
allocated for the variable.

At the same time, storage isWhen an automatic declaration isiollowed by a constant, the automatic variable is also initialized to the base of an automatic vector of the size of the constant.

The actual subscripts used to reference the vector range

from zero to the value of the constant less one.

-16-

Q.s ~nternal Declaration
The first reference

to a variable not declared as external or

automatic constitutes an internal declaration,

All internalvariables not defined as labels are flagged as undefined within aLabels are defined and initialized as follows:zunctiono

name &~oQ Hxternal Q~nLti

ons

A complete B program consists of a ser~es of external definitions.

Execution is started by the hidden sequence
maino;‘1’bus,it

exito;

is expected that one of the external definitions is afunction definition of main.
tion.

(Exit is a predefine

library func-

See section 8.0)~.~ SimDle Definition
The s~mple external definition allocates an external object andoptionally initializes it:
name {ival ~ ival ...}o~
If the external obJect is defined with no initialization, it is
Lnitialxzed with zero.

A single initialization with a constantInitializes the extrnal with the value of the constant.

Initial-ization with a name initializes the external to the address ofchat name.

L14anysuch initializations may be accessed as a vector

Dased at &name.
7.2 -—
Vector Definitions.-

An external vector definition has the following form:

““>

.

.

-17-

name ~ {constant}: 1 {ival ~ ival ...}~i
The name is initialized with the lvalue of the base of an external vector.

If the vector size is missing, zero is assumed.

Ineither case, the vector is initialized with the list of initialvalues.

Each initial value is either a constant or a name.

A

constant initial value initializes the vector element to thevalue of the constant.

The name initializes the element to theaddress of the name.

The actual size of the vector is the mal-imum of the given size and the number of initial values.
7.3 Function .
Definitions--——
function definitions have the following form:
name ~ arguments J statement
The name is initialized to the rvalue of the function.

The argu-

ments consist of a list of names separated by commas.

Each namedefines an automatic lvalue that is assigned the rvalue of thecorresponding function call actual parameters.

The statement(otten compound) defines the execution of the function when invoked.
8.0 Library Functions--I’here is a library of B functions maintained in the file/etc/libb. a.

The following is a list of those functions current-

iy in the library.

See section II of [4] for complete descrip-

tions of the functions marked with an *.
c = char(string,i);
The i-th character of the string is returned.

error = chdir(string) ;The path name represented by the string becomes the current

-18-~;fectory.

A negative number returned indicates an error.

error = chmod(string, mode);
The file specified by the string has its mode changed tothe mode argument. A negative number returned indicates anerror.
(*)
error = chown(string, owner);
The file specified by the string has its owner changed tothe owner argument. A negative number returned indicatesan error.
(*)
error = close(file) ;The open file specified by the file argument is closed.
(*)
negative number returned indicates an error.

A

file = creat(string, mode);
The file specified by the string is either truncated or
created in the mode specified depending on its prior existance. In both cases, the file is opened for writing and afile descriptor is returned. A negative number returned
indicates an error.
(*),
Ctlme(tlme, date);
The system time (60-ths of a second) represented in the
two-word vector time is converted to a 16-character date in
the 8-word v~ctor date. The,,converted date has the following format: Mmm dd hh:mm:ss .
execl(string, argO, argl$ .Oss o);
The current process is replaced by the execution of thefile specified by string. The arg-i strings are passed as(*)
arguments. A return indicates an error.
execv(string, argv, count);
The current process is replaced by the execution of thefile specified by string. The vector of strings of lengthcount are passed as arguments. A return indicates an error. (*)
exit( );
The current process is terminated.

(*)

error = fork( );The current process splits into two. The child process isreturned a zero. The parent process is returned the process ID of the child. A negative number returned indicates(*)
an error.
error = fstat(file, status);
The i-node of the open file designated by file is put inthe 20-word vector status. A negative number returned

“’)

-19-

indicates an error.

(*)

char = getchar( );The next character form the standard input file is returned. The character ‘*e’ is returned for an end-of-file.
oid = getuido;
The user-lD of the current process is returned.

(*)

error = gtty(file, ttystat);
The teletype modes of the open file designated by file isreturned in the 3-word vector tt stat. A negative number
returned indicates an error.
(*Yichar(string, i, char);
The character char is stored in the i-th character of thestring.
error = link(stringl, string2);
The pathname specified by string2 is created such that it
is a link to the existing file specified by stringl . A
negative number returned indicates an error.
(*)
error = mkdir(string, mode);
The directory specified by the string is made to exist withthe specified access mode. A negative number returned
indicates an error.
(*)
file = open(string, mode);
The file specified by the string is opened for reading if
mode is zero, for writing if mode is not zero. The open
file designator is returned. A negative number returned
indicates an error.
(*)
printf(format, argl, ...).
See section 9.3 below.
printn(number, base);
See section 9.1 below.
putchar(char) ;The character char is written on the standard output file.
nread = read(file, buffer, count);
Count bytes are read into the vector buffer from the open
file designated by file. The actual number of bytes readare returned. A negative number returned indicates anerror.
(*)
error = Seek(filet offset, pointer);
The I/C)pointer on the open file designated by file is set
to the value of the designated pointer plus the offset. A
pointer of zero designates the beginning of the file. A

.

.

-20-

pointer of one designates the current 1/0 pointer. A
pointer of two designates the end of the file. A negative(*)
number returned indicates an error.
error = setuid(id);The user-IL) of the current process is set to id.
(*)
tive number returned indicates an error.

A nega-error = stat(string, status);
The i-node of the file specified by the string is put inthe 20-word vector status. A negative number returned
indicates an error.
(*)
error = stty(file, ttystat);
The teletype modes of the open file designated by file isset from the 3-word vector ttystat. A negative number(i+)
returned indicates an error.
time(timev);
The current system time is returned in the 2-word vector
timev.
(*)
error = unlink(string) ;The link specified by the string is removed.
number returned indicates an error.
(*)

A negative

error = wait( );The current process is suspended until one of its childprocesses terminates. At that time, the child’s process-ID
is returned. A negative number returned indicates an error. (*)
nwrite = write(file, buffer, count);
Count bytes are written out of the vector buffer on the
open file designated by file. The actual number of bytes
writqen are returned. A negative number returned indicates(*)
an error.
Besides the functions available from the library, there is apredefinegram.

external vector named argv included with every pro-

The size of argv is argv~O]+l.

The elements

argv [1] ...argv[argv[O]] are the parameter strings as passed byt“he system in the execution of the current process.
in II of [4])~.~ Exam~les(See shell

.

-21-

The examples appear exactly as given to B.
9.1--/* The following function will print a non-negative number, n, tothe base b, where 2<=b<=10, This routine uses the fact thatin the ANSCII character set, the digits O to 9 have sequential
code values. */printn(n,b) {extrn putchar;auto a;if(a=n/b) /* assignment, not test for equality */printn(a, b); /* recursive */putchar(n%b + O’);}/* The following program will calculate the constant e-2 to about
4000 decimal digits, and print it 50 characters to the line ingroups of 5 characters. The method is simple output conversion of the expansion
1 +1
m
m+
““” = ““’”””
where the bases of the digits are 2, 3, 4, ... */maino {
extrn putchar, n, v;
auto i, c, CO1, a;= Col = o;~hile(i<n)
v[i++] s 1;

while(col<2*n)
a s n+l ;{~h~l~(~<~j {c =+ v[i] *lo;v[i++] = c%a;c =/ a--;1$utchar(c+’O’ );if(l(++col%5))
putchar(col%50?’
1putchar(’*n*n ‘);}V[2000] ;n 2000;‘: ‘*n’);-22-/* The following function is a general formatting, printing, andconversion subroutine. The first argument is a format string.
Character sequences,of the form ‘%x’ are interpreted and cause
conversion of type x’ of the next argument, other character
sequences are printed verbatim. Thus‘“>

printf(’’delta is %d*n”, delta);
will convert the variable delta to decimal (%d) and print thestring with the converted form of delta in place of %d. The
conversions %d-decimal, %o-octal, *s-string and %c-characterare allowed.
This program calls upon the function ‘printn’. (see section
9.1) */
printf(fmt, x1 ,x2,x3,x4,x5,x6,x7,x8,x9)
extrn printn, char, putchar;auto adx, x~ Cs is j;i=O; /* fmt index */adx = &xl; /* argument pointer */loop :
while((c=char(tmt,i++) ) != ‘x’) {if(c == ‘*e’)return;putchar(c);1x= *adx++;
switch C = char(fmt,i++) {case‘d’: /* decimal */case ‘o’: /* octal */if(x < O) {x= -x ;
putchar( ’-’);}
printn(x, c==’o’?8:1O);
goto loop;

case ‘c’ : /* char */putchar(x);goto loop;
case

‘s’:

/*

string */~h~l~~(c=char(x, j++)) != ‘*e’)
putchar(c);goto loop;}
putchar( ‘%’);

{

“

-23-

i--;
adx--;
goto loop;
1
Q.(J Usaqe
Currently on UNIX, there is no B command.
must be executed piecemeal.

The B compiler phases

The first phase turns a B source

program into an intermediate language.
/etc/bc source interm
The next phase turns the intermediate language into assembler
source, at which time the intermediate language can be removed.
/etc/bainterm
rm intermasource

The next phase assembles the assembler source into the object
tile a.out.

After this the a.out file can be renamed and theassembler source file can be removed.
as asource
mv a.out object
rm asource

The last phase loads the various object files with the necessaryii”braries in the desired order.
ld object /etc/brtl -lb /etc/bilib /etc/brt2
Now a.out contains the completely lmund and loaded program andcan “beexecuted.
a ●ut

A canned sequence of shell commands exists invoked as follows:
sh /usr/b/rc x
It will compile, convert, assemble and load the file x.b into the
executable file a.out.

.

-24-

~2.Q Imdementatlon

q~d Debuq~inq

A B program is implemented as a reverse Polish threaded “codeinterpreter: The object code consists of a series of addresses ofinterpreter subroutines.

Machine register 3 is dedicated as theinterpreter program counter.

Machine register 4 is dedicated astne interpreter display pointer.

The display pointer points totne base of the current stack frame.

The first word of eachstack frame is a pointer to the previous stack frame (priordisplay pointer.) The second word in each frame is is the saved
interpreter program counter (return point of the call creating
the frame.) Automatic variables start at the third word of eachframe.

Machine register 5 ispointer.

dedicated as the interpreter stack

The machine stack pointer plays no role in the in-terpretation.

An example source code segment, object code andinterpreter subroutines follow:
automatic s external + 100.;
va;

4

/

lvalue of first automatic onstackx; ●xternalc; 100.
bl2
bl**/ rvalue/ rvalue/ binary/ binary

mov
add
asr
mov
jmp

(r3)+,r0
r4,rO
rO
r0,(r5)+*(r3)+/ dp+offset of automatic/ lvalues are word addresses

mov
jmp

*(r3)+,(r5)+*(r3)+

mov(r3)+, (r5)+of external on stackof constant on stack
operator #12 (+)
operator #1 (=)

●

va:

x:

c:

/ linkage between subroutines

.

.

.

-25-

jxnp

*(r3)+

addjmp-(r5),-2(r5)*(r3)+

mov
mov
asl
mov
mov
jmp

-(r5),r0-(r5),rl
rl
rO,(rl)r0,(r5)+*(r3)+b12:

D1 :‘l-he above/ rvalue/ lvalue/ now byte address/ actual ’assignment/ = returns an rvalue

code as compared to the obvious 3 instruction directly

executed equivalent gives the approximate 5:1 speed and 2:1 space
penalties one pays in using B.
The salient features for debugging are then:1.

Machine r4 is the display pointer and can be used to trace
function calls and determine automatic variable values at
each call.

2. Machine r3 is the current program counter and can be used
to determine the current point of execution.
3. All externals are globals with their variable names prefixed by ‘.’.

Thus the debugger[4] can be used directly

to give values of external variables.
4. All data lvalues are word addresses and therefore notdirectly examinable by the debugger.

(See 8 request in Iof [4])
13.0 hasties.-—
This section describes the ‘glitches’ found in all languages, butrarely reported.
1. Tne compiler makes sense of certain expressions with

#’

-26-

operators in ambiguous cases (e.g. a+++b) but not others
even in unambiguous cases (e.g. a+++++ b).
The B assembler /etc/ba does not correctly2.

handleS:lblecombinations of intermediate language.
is undefined symbols/etc/ba.

intheassembly

all pos-

The symptomof the output from

This is rare.

3. I’heB interpreter /etc/bilib is really a library of threaded code segmentso

The following code segments have not yet‘beenwritten:
bl03
bl04
bl 05
bl06
b107
bl10

=&
===
=1=
=<=
=<
:;=

bill

b120

=/

4. Initialization of external variables with addresses of other externals is not possible due to a loader deficiency.
5 , Since externals are implemented as globals with names preceeded by ‘.’, the external

names‘byte’,‘endif ’, ‘even’and ‘globl’ conflict with assembler pseodooperations

andshould be avoided.

aoQ

Diagnostics

tiiaynostics consist of two letters, an optional name, and asource line number.

Due to the free format of the source, thesource line number might be high.
diagnostics.
error

name

~eaninq$)--{} imbalance

The following is a list of the

.

-27-

()

*/

i]

>C
>e
>i
>s
ex
iv
rd
Sx
un
xx

------.
----

namekeywordname--Ml-l 271-KT-pdp
Attached
References() imbalance)U */ imbalance[] imbalancecase table overflow (fatal)
expression stack overflow (fatal)
label table overflow (fatal)
symbol table overflow (fatal)
expression syntax
rvalue where lvalue expectedname redeclaration,
statement syntax
undefined nameexternal syntax

K. Thompson

-28-

References
1.

Richards, M.” The BCP~ Reference Manual.
MO099.

2. Canaday, R.H. and Ritchie, D.M.
MM 69-1371/1373-7/12.
J. Ritchie, D.M.
4.

Multics repository

Bell Laboratories —BCPL.

The UNIX ~ime
Sharinq Svstem. MM 71-1273-4.
———

Thompson, K. and Ritchie, D.M.
Available by arrangement.

UNIX Programmer’s..— Manual.