Reference Manual
Reference Manual
Bjarne S1roumup
AT&T Bell Laboratories
Murray Hill, New Jersey 07974
ABSTRACT
1. INTRODUCTION 1
2. LEXICAL CONVENTIONS • 1
2.1 Comments • 1
2.2 Identifiers (Names) 1
2.3 Keywords 1
2.4 Constants 1
2.5 Strings 2
2.6 Hardware charactcrlstic:s 3
3. SYNTAX NOTATION 3
4. WHAT'S IN A NA.ME? 3
4.1 Scopes 3
4.2 Storage classes 4
4.3 Fundamental types 4
4.4 Derived types • 4
S. OBJECTS AND LVALUES s
6. CONVERSIONS s
6.1 Charaeters and integers 5
6.2 Float and double • 5
6.3 Floating and integral 5
6.4 Pointers and integers 5
6.5 Unsigned 5
6.6 Arithmetic conversions • 6
6.7 Void 6
7. EXPRESSIONS 6
7.1 Primary expressions • 7
7.2 Unary operators 8
7.3 Multiplicative operaton 10
7.4 Additive operators 10
7.5 Shift operators 11
7.6 Relational operators 11
7.7 Equality operators 11
7.8 Bitwisc AND operator 11
7.9 Bitwise exclusive OR operator 12
7.10 Bitwisc inclusive OR operator 12
7.11 Logical A.."ID operator 12
7.12 Logical OR operator 12
7.13 Conditional operator 12
7.14 Assignment operators 12
7.15 Comma operator • 13
7.16 Overloaded operators 13
8. DECLARATIONS 14
8.1 Scope and storage class specifiers 14
8.2 Type specifiers 15
8.3 Declarators 16
8.4 Meaning of declarators • 17
8.5 Class declarations 19
8.6 Initialization 28
8.7 Type names 30
.. i -
8.8 Typedcf 31
8.9 Overloaded function names 32
8.10 Enumeration declarations 33
(~_ 8.11 Asm declaration 33
9. STATEMENTS 33
9.1 Expression statemcnt 33
9.2 Compound statement, or block 34
9.3 Conditional statement 34
9.4 While statement 34
9.S Do statement • . 34
(~ 9.6 For statement • 34
\___ 9.7 Switch statement • 35
9.8 Break statement 35
9.9 Continue statemcnt 35
9.10 Retum statement 35
9.11 Ooto statcment 36
9. l2 Labelcd statement 36
9.13 Null statement 36
9.14 Delete statement • 36
9.15 Declaration statement 36
10. EXTERNAL DEFINmONS 37
10:1 Fun.ction definitions • 37
10.2 Extcmal data definitions 38
11. SCOPE RULES • 38
12. CO:MPlLER CONTROL UNES 38
12.1 Token replacement 38
12.2 File inclusion • 38
12.3 Conditional compilation 39
12.4 Line control 39
13. IMPIJcrr DECLARATIONS 39
14. TYPES REVISITED 39
14.1 Classes • 39
14.2 Functions 40
14.3 Arrays, pointers, and subscripting 40
14.4 Explicit pointer conversions 40
15. CONSTANT EXPRESSIONS 41
16. PORTABILttY CONSIDERATIONS • 41
17. FREE STORE 42
18. SYITTAX SUMMAY 42
18.1 Experessions 43
18.2 Dcclarations 44
18.3 Statemenis • 47
18.4 Extemal de.finitions • 47
18.5 Preprocessor 48
19. DIFFERENCES FROM C 48
19.l Extensions • 48
19.2 Summary of incompatibilities • 48
19.3 Anachronisms 49
- ii -
The C+ + Programming Language - Reference Manual
Bjarne Stroustru.p
AT&T Bell Laboratorles
Mw:ray Hill, New Jersey 07974
1. INTRODUCTION
This manual descrlbes the C+ + programming language. C+ + is C as desc:ribed in the C bookt
extended with classes, inline funetions, operator overloading, function name overloading, constant
types, references, free store management, function argument cbecking, and a new function
definition syntax. The differcnces betwecn C++ and C are summarized in §19. This manual
describes the language as of October 1984.
2. LEXICAL CONVENTIONS
There are six classes of tokens: ident:ifiers, keywords, constants, strings, opera.tors, and other
separators. Blanks, tabs, new-lines, and comments (collectivcly, "white spacctt) as desc:ribcd
below are ignored exœpt as they serve to separate tokens. Some white spaœ is required to
separate otherwise adjacent identifiers, keywords, and constants.
If the input stream has bcen parsed into tokens up to a given charactcr, the next token is taken to
include the longest string of characten wbich could possibly constitute a token.
2.1 Comments
The cbaracters / * introduce a comment, wbich temùnates with the characters •/. Comments do
not nest.
2.2 Identifiers (Names)
An identifier is an arbitrarily long sequenœ of letters and digits; the first character must be a
letter; the underscore _ counts as a letter. Upper- and lower-case letters are different.
2.3 Kcywords
The following identifiers are reserved for use as keywords, and may not be used otherwise:
asm auto break caae char claas conat
default delete do double elae enmn extern
float for friend. goto if inline int
long new operato:r overload. public registe:r return
short aizeof atatic atruct awitch this typed.ef
union unsigned virtual void while
(_ 2.4 Constants
Toere are several kinds of constants, as listed below. Hardware characterlstics that affect sizes are
summarized in §2.6.
2.4.1 Integer constants
An integer constant consisting of a sequence of digits is taken to be octal if it begins with o (digit
zero), decimal otherwise. The digits 8 and gare not octal digits. A sequence of digits preœded by
Dx or ox (digit zero) is taken to be a hexadecimal integer. The hexadecimal digits include a or A
(_ through f or F with values 10 through 15. A decimal constant wbose value exœeds the largest
+ This manual is or~ed like the rcfermce manual in The C Programming Longuoge by Brian W.
Kemighan and Dennis M. Ritchie, Prentice Hall, 1918.
C++ Reference Manual 2
signed integer is taken to be long; an octal or hex constant which exceeds the largest unsigned
integer is llk:ewise taken to be long; othcrwise integer constants are taken to be int.
2.4.2 Explici.t long constants
A declmal, octal, or hexadecimal integer constant immedi.ately followed by l (letter ell) or L is a
long constant.
2.4.3 Character constants
A character constant is a character enclosed in single quotes, as in 'x' . The value of a character
constant is the numerlcal value of the character in the machine's character set. Cbaractcr constants
are taken to be int.
Certain non-araphic characters, the single quote ', and the backslash \, may be represented
according to the following table of escape sequences:
new-line NL (LF) \n
horizontal tab HI' \t
vertical tab VT \v
backspace m \b
caniage retum CR ~
form feed FF 'f'
backslash
single quote
\
, ,,
\\
2. 6 Hardware characterlstics
The following table summarizes certain hardware properties that vary from machine to machine.
(_ DEC VAX Motorola 68000 IBM370 AT&T3B
ASCII ASCII EBCDJC ASCn
char 8 bits 8 bits 8 bits 8 bits
int 32 16 32 32
short 16 16 16 16
long 32 32 32 32
float 32 32 32 32
double 64 64 64 64
pointer 32 32 24 32
float range :t 10:38 ±10=38 :t:10=76 ±10=38
double range ±10=38 ±10=38 :tlO:t:76 :tlO:t: 308
field type signed unsigned unsigned unsigned
field order right-to-left left•t?-ril!tt left-to-right left-to-right
char simed unsitmed unsimed
3. SYNTAX NOTATION
In the syntax notation uscd in this manual, syntactic categories are indicated by italic type, and
literal words and characters in constant width type. Alternatives are listed on scparate Unes.
An optional terminal or non-terminal symbol is indicated by the subscript "opt," so that
{ expressionopt }
indicates an optional expression enclosed in braces. The syntax is summa:rized in §19.
4. \VHAT'S IN A NAME?
A name denotes an object, a function, a type, or a value. A name can only be used within a
region of program text called its scopc. A name has a type which determines its use. An abject is
a region of storage. An object bas a storage class which deter:m.incs its lifetime. 'Ibe meaning of
the values found in an object is determined by the type of the name used to acœss it.
4.1 Scopes
Thcre are four kinds of se.ope: local, file, program, and class.
Local: A name declared in a block is local to that block and can only be used in it after the
point of declaration and in blocks enclosed by it. Exceptions are labels (§9.12) which can be
used anywhere in the functian in which they are declared, and function names which be.long
to the file or program scopc. Names of formal parameters for a function arc treated as if
they wcrc declared in the outermost block of that function.
File: A name declared outside any block (§9.2) or class (§8.S) can be used in the file in
which it is declared after the point of declaration. It is not accessible from other files in a
multi-file program unlcss it is explicitly declared extern.
Program: A name declared extern is common to every file in a multi-file program, so that a
dcclaration of that name in another file refm to the same object (§5), fonction (§10.1), type
(§8.7), or value (18.10).
Class: The name of a class mcmber is local to its class and can only be used either in a
member function of that class, for an object of its class using the • operator (§7.1), or for a
pointer to an object of its class using the •> operator (§7.1). Static class members (§8.S.1)
and function members can also be rcferred to where the name of their class is in scope by
using the : : operator (§7 .1).
C++ Reference Manual 4
A name may be hidden by an explicit decl.aration of that same name in a block or cl.ass. A name in
a block or class c:an only be hidden by a name declared in an enclosed block or class. A hidden
non-local name can still be used when its scope is speclfied using the : : opcrator; sec §7.1.
4.2 Storage classes
There are twa declarable storagc classes: automatic and static.
Automatic abjects are local to each invocation of a block and are discarded u.pon exit from it.
Static abjects exist and retain their values throughout the execution of the entire program.
Some abjects are not associated with names and their lifetimes are explicitly controlled using the
new and delete operators; sec §7.2, §9.14, and §17.
4.3 Fundamental types
Objects declared as characten (char) are large enough to store any member of the
implementation's character set, and if a gcnuine character from tbat character set is stored in a
character variable, its value is equivalent to the integer code for that character. Other. quanti.tics
may be stored into character variables, but the implementation is machine-dependent.
Up to three sizes of integcr, declared ahort int, int, and long- int, are available. Longer
integers provide no less storage t1um shorter ones, but the implcmentation may make either shon
integers, or long integers, or both, equivalent to plain integers. "Plain" integers bave the natural
size suggested by the host machine architecture; the other sizes are provided to meet special needs.
Each enumeration (§8.9) is a set of named CODStants. The properties of an enwn are identical to
those of an int.
Unsigned integers, declarcd unsigned., obey the laws of arithmetic modulo 2n where n is the
number of bits in the representation.
Single-precision floatina point (float) and double-precision tloatin& point (double) may be
synonymous in some implementations.
Because objects of the foregoing types can usefully be interpreted as numbers, they will be referred
to as arithmenc typeS. Types char, int of all sizes, and enwn will collectively be callcd tnzegral
types. float and double will collectively be calledfloating types.
The void type speclfies an empty set of values; sec §6.7.
4.4 Derived types
Besides the fundamental arithmetic types there is a conceptually infinite number of derived types
(_ constructed from the fundamental types in the following ways:
arrays of objects of a given type;
Junctions which take argwnents of given types and return objects of a given type;
pointers to objects of a given type;
references to objects of a given type;
constants which are values of a givcn type;
classes containing a sequence of abjects of various types, a set of functions for manipulating
these objects, and a set of restrictions on the access to these objects and functions;
structures which are classes without access restrictions;
unions which are structures capable of containing objects of different types at different times.
In gencral these methods of constructing objects can be applied rec:unively.
C++ Reference Manual 5
6. CONVERSIONS
A number of operators may, depending on their operands, cause conversion of the value of an
operand from one type to another. This section explains the result to be expected from such
conversions. §6.6 summarizes the conversions demanded by most ordinary operators; -it will be
supplemented as required by the discussion of each operator. §8.S.6 describes user-defined
conversions.
6.1 Characters and intcgers
A character or a shon integer may be used wherever an integer may be used. In all cases the
value is convened to an integer. Conversion of a shoner integer to a longer always involves sign
extension; integers are signed quantities. Whethcr or not sign-extension occurs for characters is
machine dependent; sec §2.6. The more expliclt type unsigned char forces the values to range
from O to a machine dependent maximum.
On machines that treat characters as signed, the characters of the ASCII set are all positive.
However, a character constant specified with an octal escape suffers sign extension and may appear
negative; for example, '\377' bas the value -1.
\Vhen a longer integcr is converted to a shorter or to a char, it is truncated on the left; excess bits
are simply discarded.
6.2 Float and double
Floating arithmetic is carried out as if in double·precision. Conversions between single-precision
and double-precision floating-point numbers are as mathematically correct as the hardware allows.
6.3 Floating and intcgral
Conversions of floating values to integral type tend to be machine-dependent; in particular the
direction of truncation of negative numbers varies from machine to machine. The result is
undefined if the value will not fit in the space provided.
(_ Conversions of integral values to floating type arc well bchavcd. Some loss of precision occurs if
the destination lacks sufficient bits.
6.4 Pointers and integers
An expression of integral type may be added to or subtracted from a pointer; in such a case the
first is converted as specified in the discussion of the addition operator.
Two pointers to objects of the same type may be subtracted; in this case the result is convened to
an int or a long- dependent on the machine; sec §7.4.
(__ 6.5 Unsigned
\Vhenever an unsigned integer and a plain integer are combined, the plain integer is converted to
unsigned and the result is unsiped. The value is the least unsigned integer congruent to the
signed integer (modulo 2wordsize). In a 2's complement repre.sentation, tbis conversion is
conccptual and there is no actual change in the bit pattern.
C+ + Reference Manual 6
\Vhen an unsigned integer is converted to long, the value of the result is the same numerically as
that of the unsigned integer. Thus the conversion amounts to padding with zeros on the left.
(_ 6.6 Arithmetic conversions
A great many operators cause conversions and yicld result types in a similar way. This pattern
will be called the "usual arithmetic conversions."
First, any operands of type char, unsigned char, or short are converted to int, and
any of type float is convertcd to doul)le.
Then, if either operand is doul>le, the other is converted to double and that is the type of
the result.
Otherwise, if either operand is unsigned long the other is converted to unsigned long
and that is the type of the result.
Otherwise, if either operand is long, the othcr is converted to long and that is the type of
the rcsult.
Otherwise, if either operand is unsigned, the other is converted to unsigned and that is
the type of the rcsult.
Otherwisc, bath operands must be int, and that is the type of the result.
6.7 Void
The (nonexistent) value of a voie! objcct may not be used in any way, and ncitber explicit nor
implicit conversions may be applicd. Because a void expression denotes a nonexistent value, such
an expression may be used only as an expression statement (§9.1) or as the left operand of a
comma expression (§7.15).
An expression may be convcrted to type void by use of a cast. For example, this makcs explicit
the discarding of the value of a function call uscd as an expression statement.
A abject of type void• (pointer to void) can be used to point to abjects of unknown type.
7. EXPRESSIONS
The preccdence of expression operators is the same as the order of the major subscctions of this
section, highest preccdencc first. Thus, for examplc, the expressions rcfcrrcd to as the operands of
+ (§7.4) are those expressions defined in §§7.1-7.4. Within each subsection, the operators have
the same precedence. Left- or right-associativity is specified in each subsection for the operators
discusscd therein. The precedence and associativity of all the expression operators is summarized
in the grammar of §18.
Otherwise the order of evaluation of expressions is undefined. In particular the compiler considers
itself free to compute subexpressions in the order it believes most efficient, even if the
subcxpressions involve side effects. The order in which side effects take place is unspecified.
Expressions involving a commutative and associative operator (*, +, &., 1, A) may be rearranged
arbitrarily, evcn in the presence of parenthcses; to force a particular order of evaluation an explicit
temporary must be used.
Toe bandling of ovcrflow and divide check in expression evaluation is macbine-dependent. Most
C_ existing implementations of C++ ignore integer overflows; treatmcnt of division by 0, and ail
floating-point exceptions, varies between machines, and is usually adjustable by a library function.
In addition to the standard meanings described in §7.2-7.15 operators may be overloaded, that is
given meanings when applied to user-dcfined types; see §7 .16.
C+ + Reference Manual 7
identical (by definition) to * C{E 1 ) + <E2 ) ) • All the clues needed to understand this notation are
contained in this section together with the discussions in§§ 7.1, 7.2, and 7.4 on identificrs, *, and
+ respectively; §14.3 below summarlzes the implications.
C A function call is a primary expression followed by parenthescs containing a possibly empty,
comma-separated list ·of expressions which constitutc the actual arguments to the function. The
primary expression must be of type "function returning ... ", and the result of the function call is
of type " ... ". A hitherto unseen identifier followed immcdiatcly by a left parenthesis is
contextually declared to represent a function returning an integer. Its argument type will be
declared to that of the argument list of the call.
The actual arguments are compared with the formai arguments and conversions are performed as if
(_ the forma! argument were initializcd with its actual argument (see §8.6).
ln preparing for a call to a function, a copy is made of each actual parametcr. A function may
change the values of its forma! parametcrs, but thesc changes cannot affect the values of the actual
parameters. On the other band, it is poss10le to passa pointer or a referenœ on the understanding
that the function may change the value of the object to whicb the pointer or referenœ points. An
array name is a pointer expression.
A function may be declared to accept fewer arguments or more arguments than are specified in the
function declaration; sec §8.4. Any actUal argument of type :float for which there is no forma!
argument are converted to double before the call; any of type char or short are converted to
int; and as usual, array names are convertcd to pointers. The order of evaluation of arguments is
undefined by the language; take note that the various compilers differ.
&cursive ca1ls to any function are permitted.
A primary expression followed by a dot followed by an identifier (or an identifier qualified by a
typedcf-name using the : : operator) is an expression. The first expression must be a class object,
and the identifier must name a member of that class. The value is the named member of the
object, and it is an !value if the first expression is an !value. Note that "class objects" can be
structures (§8.5.11) and unions (§8.5.12).
A primary expression followed by an arrow ( • >) followed by an identifier (or an identifier
qualified by a typedef-name using the : : operator) is an expression. The first expression must be
a pointer to a class object and the identifier must name a member of that class. The result is an
!value referring to the named member of the class to which the pointer expression points. Thus
the expression E1•>MOS is the same as ( •E1) .MOS. Casses are discussed in §8.5.
If a primary expression yields a value of type "referenœ to ... " (sce §8.4 and §8.6.3) that value is
immediately dereferenccd so that the value of the expression is · the objcct denoted by the
(_ reference. H this object is also a referenœ, it too will be dereferenced, and so on. A referenœ
can be thought of as a name of an object; sce §8.6.3.
7.2 Unary operators
Expressions with unary operators group riaht·to·left.
C++ Reference Manual 9
unary-expression:
unary-operator expression
expression + +
expression - -
C ryp,-name ) expression
simple-rype--name ( expression-list )
si zeof expression
sizeof C typt·name
new typtM1ame
new ( type-nome
unary-operator: one of
* L - 1 • ++
The unary * operator means indirection: the expression must be a pointer, and the result is an
lvalue rderring to the object to which the expression points. If the type of the expression is
"pointer to ... ", the type of the result is " ... ".
The result of the unary & operator is a pointer to the object referred to by the operand. The
operand must be an lvalue. If the type of the expression is " ... ,, , the type of the result is
"pointer to ... ".
The result of the unary - operator is the negative of its operand. The operand must be of integral
type. The usual arlthmetic conversions are pcrformcd. The negative of an unsigned quantity is
computed by subtractina its value from 2n, where n is the number of bits in an int. 'Ihere is no
unary + operator.
The result of the logical negation operator J is 1 if the value of its operand is 0, 0 if the value of
its operand is non-zero. The type of the result is int. It is applicable to any arlthmetic type or to
pointers.
The • operator yields the one's complement of its operand.. The usual arithmetic conversions are
performed. The type of the operand must be integral.
The operand of prefix ++ is incremented. The operand must be an !value. The value is the new
value of the operand, but is not an !value. The expression ++xis equivalent to x+•1. See the
discussions of addition (§7.4) and assignment operators (§7 .14) for information on conversions.
The operand of pretix - - is decremented analogously to the prefix + + operator.
The value obtained by applying a postfix + + is the value of the ope.rand. The operand must be an
lvaluc. After the result is noted, the objcct is incrcmentcd in the same manner as for the prefix ++
operator. The type of the result is the same as the type of the operand.
The value obtained by applying a postfix -- is the value of the operand. The operand must be an
!value. After the result is noted, the object is decremented in the manner as for the prctix --
operator. The type of the result is the same as the type of the operand.
A simple-typt-name (§8.2) followed by a parenthesized expression causes the value of the
expression to be c.onverted to the named type. To express conversion to a type that does not have
a simple name the rype-name (§8.7) must be parenthesized; ùt this case the expression need not be
parenthesized. This construction is called a cast. The mcthod for defining conversions for user-
defincd types (classes) is desc:rlbcd in §8.S.S and §8.5.6. For user-defined types an expression list,
rather than: a simple expression, can be used; sce §8.S.S.
The s izeof operator yields the size, in bytes, of its operand. (A byte is undefined by the
language except in tcrms of the value of sizeof. However, in all existing implemcntations a byte
is the space required to hold a char.) When applied to an array, the result is the total number of
bytes in the array. The size is detcrmined from the declarations of the objects in the expression.
This expression is semantically an uns:lgned constant and may be used anywhere a constant is
C+ + Re/erence Manu.al 10
required. Its major use is in communication with routines likc storage ailocators and 1/0 systems.
The sizeof operator may also be applied to a parenthesized type name. In that case it yields the
size, in bytes, of an abject of the indicated type.
The new operator creates an object of the type-name (sec §8.7) to wbich it is applied. The lifetime
of an object crcated by new is not restricted to the scope in which it is created. The new operator
returns a pointer to the object it created. When applied to an object of type T it therefore gcnerally
returns a value of type T•. However, the type yielded for an array type T [ ] is T• • For example,
both new int and new int [ 10] return an int•. See §17 for details of how the free store is
managed.
7. 3 Multiplicative operators
The multiplicative operators •, /, and " group left-to-rlght. The usual arithmetic conversions are
performed.
multiplicative-expression:
expression * expression
expression / expression
expression " expression
The binary * opcrator indicates multiplication. The * operator is associative and expressions with
several multiplications at the same lcvel may be rearranged by the compiler.
The binary / operator indicates division. When positive integers are divided truncation is toward
0, but the form of truncation is machine-dependent if either operand is negative. On ail machines
covered by this manual, the remainder bas the same sign as the dividend. It is always truc that
( a/b) •b + aXb is equal to a (if bis not 0).
The binary" operator yields the remaindcr from the division of the first expression by the second.
Toc usual arithmetic conversions arc performed. The operands must not be floating.
7.4 Additive opcrators
The additive operators + and - group left-to-rlght. The usual arithmetic conversions are
performed. There arc somc additional type possibilities for each operator.
additive-expression:
expression + expression
expression - expression
The result of the + operator is the sum of the operands. A pointer to an abject in an array and a
value of any integral type may be added. The latter is in ail cases converted to an address offset
by multiplying it by the lcngth of the abject to wbich the pointer points. The result is a pointer of
the same type as the original pointer, and which points to another object in the same array,
appropriately offset from the original object. Tous if P is a pointer to an abject in an array, the
expression P + 1 is a pointer to the next object in the array.
No further type combinations are allowed for pointers.
The + operator is associative and expressions with several additions at the samc lcvel may be
rearranged by the compiler.
(_ The result of the - operator is the differencc of the operands. The usual arithmetic conversions
are performed. Additionally, a value of any integral type may be subtracted from a pointer, and
then the same conversions as for addition apply.
If two pointers to abjects of the same type are subtracted, the result is converted (by division by
the length of the object) to an integer representing the number of abjects separating the pointed·to
objccts. Depending on the machine the resulting intcger may be of type int or type long; sec
§2.6. This conversion will in gencral give unexpccted results unless the pointers point to objccts in
C+ + Reference Manual 11
the same array, since pointers, evcn to objects of the same type, do not necessarily differ by a
multiple of the object-lenam.
7 .S Shift operators
The shift operators < < and > > group lefMo-rlght. Both perform the usual aritbmetic conversions
on their operands, each of which must be integral. Then the right operand is converted to int;
the type of the result is that of the left operand. The result is undefined if the right operand is
negative, or greater than or equal to the lcnath of the object in bits.
shift-expression:
expression < < expression
expression > > expression
The value of E1 « E2 is E1 (interpreted as a bit pattern) left-shifted E2 bits; vacated bits are 0-
filled. The value of E 1 » E2 is E 1 right-shifted E2 bit positions. The rlght shift is ,uaranteed
to be logical (0-fill) if E1 is unsigned; otherwise it may be arithmetic (fill by a copy of the sign
bit).
7.6 Relational operators
The relational operators group left-to-right, but tbis fact is not very use.ful; a<b<c does not mean
what it seems to.
relational-expression:
expressitJn < uprusion
apressitJn > ex.pression
expression < • expression
expression > • expression
The operators < (less than), > (greater than), o (less than or equal to) and >• (sreater than or
equal to) all yield O if the spedfied relation is false and l if it is truc. The type of the result is
int. The usual arithmetic conversions are performed. Two pointers may be compared; the result
depends on the relative locations in the address spaœ of the pointed-to abjects. Pointer
comparison is portable only wben the pointers point to abjects in the same array.
7. 7 Equality operaton
equality-expr,ssion:
expression •• expression
expressitJn. l • expression
The •• (equal to} and the ! • (not equal to) operators are exactly analogous to the relational
operators except for their lower precedence. (Thus a<b •• cccl is 1 wbenever a<b and c<cl
have the same truth-value.)
A pointer may be compared to an integer only if the integer is the constant O. A pointer to which
0 bas bcen assigned is guaranteed not to point to any object, and will appear to be equal to O; in
conventional usage, such a pointer is considered to be null.
7 .8 Bitwisc AND operator
and-expression:
expressitJn &. uprusitJn
The&. operator is associative and expressions involving & may be rearranged. The usual arithmetic
conversions ·are performed; the result is the bitwise AND function of the operands. The operator
applies only to integral operands.
C+ + Reference Manual 12
assignmem-expression:
expression assignment-operaror expression
assign:mem-operaror: one of
• +• -· •• /• %• >>• <<• &• A. 1.
In the simple assignment with •, the value of the expression replaces that of the object referred to
by the left hand operand. If both operands have arithmetic type, the rlght operand is converted to
the type of the left preparatory to the assignment. Both opcnmds may be class objects of the same
type or pointer abjects of the same type. Objects of some derived classes cannot be assigned; sec
§8.5.3. A pointer to a class may be assigned to a pointer to a public base class of that class; sec
§8.5.3. Any pointer may be assigned to a pointer of type void•. The constant Omay be assigned
to a pointer, and it is guaranteed that this value will produœ a null pointer distinguishable from a
pointer to any abject.
Since a reference is implicltly dereferenccd, assignment to a abject of type "reference to ... "
assigns to the object denoted by the reference.
The behavior of an expression of the form E 1 op • E2 may be infcrred by ta.king it as equivalent
to E 1 • E 1 op CE2); however, E 1 is evaluated only once. ln +a and -•, the left operand may
be a pointer, in which case the (integral) rlght operand is converted as explained in §7.4; all right
operands and all non-pointer left operands must have arithmetic type.
7.15 Comma opcrator
comnu:z-upression:
expression , expression
A pair of expressions separated by a comma is evaluated left-to-rlght and the value of the left
expression is discarded. The type and value of the result are the type and value of the rlght
operand. This opcrator groups left-to-right. In contexts where comma is given a speclal meaning,
for example in lists of actUal arguments to functions (§7 .1) and lists of initializers (§8.6), the
comma operator as descrlbed in this section can only appear in parentheses; for example,
f(a, (t•3, t+2), c)
bas threc arguments, the second of which bas the value S.
7.16 Overloaded operators
Most operators can be declared to accept class abjects as operands (see §8.5.10). lt is not possfüle
to change the precedence of operators. It is not possible to change the xnanjng of operators when
applied to non-class objects. The pre-defined meaning of the operators • and (unary) &. when
applied to class objects can be changed.
The meanings of somc operators arc defincd to be equivalcnt to some combination of other
opcrators on the same arguments. For example, ++a means a +a 1. Such relations do not hold for
defined operators unless the user defines them that way. Some operators, for cxample assigmnent,
require an opcrand to be an lvalue; this is not rcquired for defined operators.
7.16.1 Unary opcrators
A unary operator, whether prefix or postfix, can be defined by either by a member function (see
§8.5.4) taking no arguments or a fdend function (see §8.S.9) ta.king one argument. Thus, for
any unary operator I', both d and h can be interpreted as either x.operatoz:11() or
operatortt{ x) • If both operatorlt functions arc defined the former interpretation is usai.
Wh.en the operators + + and -- are overloaded, it is not possiôle to disûnguish prefix application
from postfix application.
C+ + Reference Manual 14
8. DECLARATIONS
Declarations are used to specify the interpretation given to each identifier; they do not neœssarily
reserve storagc associated with the identifier. Dcclarations have the form
declaration:
decl-specift,rswt declarator-listopt ;
na:m,-declaratton
a.sm-declaration
The declarators in the declarator•list contain the identifien being declared. Only in c:xtemal
function definitions (§10.1) or external function declarations may the decl-specijiers be omitted.
Only wben declaring a class (§8.S) or enumcration (18.10), that is when the decl-speciftes is a
class-specifler or enum-specijier, may the declarator-list be empty. Name-declarations are described
in §8.8; asm declarations are described in §8.11.
decl-specifiers:
decl-specifter decl-specifiersopt
decl-specifier:
ss-specijier
type-specifier
fct-specift,r
friend.
typed.ef
The list must be self-consistent in a way·descnëed below.
8.1 Scope and storage class specifiers
(_ The ss-specifiers are:
ss-specijier:
auto
static
extern
regiater
C++ Reference ManlUJl 15
Declarations using the auto, static, and register specifiers also serve as definitions in that
they cause an appropriate amount of storage to be rcserved. If an extern declaration is not a
definition (that is, neither a data declaration with an initializer nor a function declaration with a
body) there must be an external definition (§10) for the given identifiers somewhere else.
A register declaration is best thought of as an auto declaration, together with a hint to the
compiler that the variables cleclared will be heavily used. The hint may be ignorcd. The address-of
operator &. cannot be applied to them.
The auto or register specifiers can only be used for names declared in a black and for formal
parameters. There can be no static funct.ions within a block, nor any static forma!
arguments. The scope of name declarcd with the static specifier outside a function or a class is
file (§4.1). The scope of the name of an object or function declared extern is program (§4.1).
At most one ss-specifler may be given in a declaration. If the ss-specifter is missing from a
declaration, the storage class is taken to be automatic inside a function and static outside.
Exception: functions are never automatic. If the ss-specifier is missing from a decl.aration, the
scope of the name is taken to be local in a block, class in a class declaration, and file elsewhere.
Exception: The scope of the name of a funct.ion that is declarcd but not defincd (§10) is taken to
be program unless it is explicitly declarcd static.
Some specifiers can only be used in function declarations and definitions:
fct-specifiers:
overload.
inline
virtual
The overload speclfier enables a sin.ale name to be used to denote several functions; see §8.9.
The inline specifier is only a hint to the compiler, does not affect the meaning of a program,
and can be ignored. lt is used to indicate that when the function is called inline substitution of the
funetion body is to be preferred to the usual fonction call implementation. lt can only be uscd in
function definitions (§10.1). A function (§8.5.2 and §8.5.9) defined within the declaration of its
class is inline by default.
The virtua.l specifier can only be used in declarations of class members; see §8.5.4.
The fr i end specifier is used to override the name hi.ding rules for class members and can only be
used within a class declaration; see §8.5.9.
The typedef specifier is used to introduœ a name for a type; see §8.8.
8.2 Type specifiers
The type-specifiers are
type-specifler:
simpl,-ryp,-Mm4
class-specljil!I'
en,nn-specifier
const
C++ Reference Manual 16
simple-rype-name:
typedef-na.me
char
( __ short
int
long
unsigned
float
double
void
The words long, short, and unsigned may be thought of as adjectives. They can be applied to
int; unsigned can also be applied to char, short, and long. The word const may be added
to any legal type-specifier. Otherwise, at most one type-specifier may be given in a declaration.
An abject of const type is not an lvalue. If the typc-specifier is missing from a declaration, it is
taken to be int.
Qass and enumeration specitiers are discussed in §8.5 and §8.10, respectively.
8.3 Declarators
The declarator-list appearing in a declaration is a comma-separated sequence of declarators, each
of which may have an initializer.
declarator-list:
init-declarator
inii-declarator , declarator-llst
init-declarator:
âeclarator initializeropt
Initializers are discussed in §8.6. The spedfiers in the dcclaration indicate the type and storage
class of the objects to which the dcclarators refer. Declarators have the syntaX:
declarator:
dname
( declarator )
* constopt declarator
&. const0 r declarator
declarator ~ argument-declaration-list
tkclarator [ constant-expressionopt J
dname:
simple-dname
typedef-name • simple-dnamt
simple-dn.amt:
identifier
typedef-name
• typedef-name
operator-function-namt
conversion-junction-namt
arg-declaration-list:
arg.declaration-list , argu:mem-declarad.on
arg,,,,,,.m.declaration
argument.declaration:
decl-sp,clflus declarat0r
decl-specifiers declarattJr • constant-expression
If the argumem.declaration-llst terminates with an ellipsis the number of arguments is only known
to be equal to or greater than the number of argument types specified; if it is empty the function
takes no arguments. All declarations for a function must agree exaetly both in the type of the
C+ + Referenct Manual 18
value retumed and in the number and type of arguments. The keyword void may be used to
indicat.e that a function takes no arguments, thus (void) is equivalent to C).
C The argumeni-declaration-lisr is used to check and convert actUal arguments in calls and to check
point.er-to-function assignments. If a constant expression is speclfied as initializer for an argument
this value is used as a default argument value. A default value for an argument cannot be
redefined by a latc:r declaration. Howevc:r, a declaration may add default values for arguments not
given such values in previous declarations. Default argument values will be used in calls where
trailing arguments are mi.ssing. In an argumeni-declaration the identifier in the declarator may be
lcft out (as in an absrraci-declarator (§8.7)). If present, the identifier can in fact never be used
since it goes out of scope at the end of the funetion declaration.
If D 1 bas the form
D [ connani-u.pression]
or
DC]
then the contained identifier bas type " . . . array of T." In the fim case the constant expression is
an expression whose value is detcrminable at compile time, and whose type is int. (Constant
expressions arc defincd in §15.) Wben several "array of" speclfications are adjacent, a multi-
dimensional array is creat.ed; the constant expressions which speclfy the bounds of the arrays may
be mi.ssing only for the :fim member of the sequenœ. This elision is useful when the array is
extc:rnal and the actual definition, which allocates storagc, is given elsewhere. The first constant-
expression may also be omined when the declarator is followed by initialization. In this case the
size is calculated from the number of initial elements supplied.
An array may be consttucted from one of the basic types, from a pointer, from a structure or
union, or from anothcr array (to gcneratc a multi·dimcnsional array).
Not all the possibilities allowed by the syntax above are permitted. The restrictions are as follows:
functions may not retum arrays or functions, although they may return pointers to such things;
there are no arrays of functions, although there may be arrays of pointers to functions.
AB an example, the declaration
int i, dp, f(), •fip(), (•pfi) ();
declares an integer i, a pointer ip to an integer, a funetion f retuming an integer, a function fip
retumin& a pointer to an integer, and a pointer pf i to a function which retums an integer. It is
espccially useful to compare the last two. The binding of •fip( ). is • <:Up()), so that the
C declaration suggests, and the same construction in an expression requiNs, the calling of a fonction
fip, and then using indirection through the (pointer) result to yield an integer. In the declarator
( •pf i) ( ) , the extra parentheses are necessary, as they are in an expression, to indicat.e that
indirection through a pointer to a funetion yiclds a function, which is then called. The functions f
and fip are declared to take no arguments, and pfi to point to· a funetion which takes no
argument.
The declaration
const a• 10, •pc • &.a, •const cpc • pc;
int b, •const cp • &.b;
declares a: a constant integer, pc: a pointer to a constant integer, cpc: a constant pointer to a
constant integer, b: an integer, and cp: a constant pointer to integer. The value of a, cpc, and cp
cannot be changcd aftc:r initialization. The value of pc can be ehanged, and so can the object
point.cd to by cp. E.xamplex of illegal operations are:
C++ Reference ManUIJI 19
A structure is a class with ail members public; see §8.S.8. A union is a structure wbich holds only
one member at a time; see §8.5.12. A member-li.st may declare data, function, class, typedef,
enum, and field mcmbers. Fields are discussed in §8.5.13. A m.ember-list may also contain
declarations adjustina the visibility of member names; see §8.5.8.
m.ember-list:
m.ember-declaration memb,r-li.stop,
m.emb,r-declaration:
decl-specifiers t m.ember-declarator initializer
function-definlll'Jn ; t opt
op
m.ember-declarmor:
declarator
identifieropt : constant-apresslon
Members that arc class abjects must be abjects of previously declared classes. ln particular, a class
cl may not contain an object of class cl, but it may contain a pointer to an object of class cl.
'l'be membcr names in different classes do not conflic:t witb cach other or with ordinary variables.
Only dcclarations of static members (§8.S.1) may contain initializers.
A simple cxample of a struct declaration is
struct tnode { .
char tword[20];
int count;
tnode •left;
tnode •right;
} ;
wbich contains an array of 20 charactets, an integer, and two pointers to similar structures. Once
tbis declaration bas been given, the declaration
tnode a, •sp;
declares a to be a tnode and ap to be a pointer to a tnod.e. With tbese declarations
ap•>count
refers to the count field of the structure to wbich sp points;
a.left
refers to the lcft subtrec pointer of the structure s; and
a.right•>tword[O]
refers to the first character of the tword. member of the right subtree of s.
8.5 .1 Static members
A data member of a class may be atatic; funetion members may not. Members may not be
auto, regiater, or extern. There is only one copy of a static member shared by a1l abjects of
the class in a program. A static me:m.ber mem of class cl can be referred to as cl : : mem, that is
without referring to an object. It exists even if no abjects of class c 1 have been crcated.
8.5.2 Member functions
A function declared as a member (witbout the friend specifier (§8.S.9) is called a member
function, and is called using the class member syntax (§7.1). For example:
C+ + Reference ManUJJ.I 21
struct tnod.e {
char tword. C2 0 J ;
int count;
C tnod.e *1eft;
tnod.e *ri9ht;
voièl set(char*, tnode• 1. tnode* r);
} ;
tnode n 1 , n2 ;
n1.aet("asd.f",&n2,O);
n2.set("ghjk",O,O);
The definition of a membcr function is considered to be w.ithin the scope of its class. This means
that it can use names of its class directly. If the definition of a membcr function is lexically
outsidc the class declaration the membcr function name must be qualified by the class name using
the rypedt/-na»N.simple-dna.me notation; see §8.3.3. Function definitions are discussed in §10.1.
For example:
void. tnode.aet{ch&r* w, tnode• l, tnod.e• r) {
count • •trlen(w);
if (abeof(tword)ocount) error("tnode string too long");
strcpy(tword,w);
left • l;
right • r;
}
Th~ function name tnode .. set spccifies that the function set is a membcr of class tnoèle. This
enables the member namcs word., count, left, and right to be used. In a mcmber function a
member name refcrs to the object for whièh the function was called. Thus, in the call
n 1 • set C ••• ) , tworcl refers to n 1 • tworèl, and in the call n2 • aet ( ••• ) it refers to
n2 •tword. ln this exam.ple, the functions strlen, error, and strcpy are assumed to be
declared clsewhere; see §10.1.
In a member function, the keyword thia points to the object for which the function is called. The
type of thia in a function whièh is the mcmber of a class cl is cl•. If mem is a man.ber of class
cl, mem and thia->mem are synonymous in a class cl member function (unless mem has been
used as the name of a local variable in an intermediate scope).
A member function may be dcfined (§10.1) in the class declaration. Placing a membcr function
definition in the class declaration is just a shorthand for declarlng it in the class declaration and
then detining it inline (§8.1} just after the class declaration. For example:
int b;
atruct x {
int f() { return b; }
int b;
} ;
means
C. int b;
struct x {
int f();
int b;
} ;
inline x.f () { return b; }
C++ Reference Manual 22
The specifier overload (§8.2) need not be used for member funetions: if a name is declared to
dcnote several funetions in a class it is overloaded (see §8.9).
( It is legal to apply the address-of operator to a member function. However, the type of the
resulting pointer to function is undefined, so that any use of it is implementation dependent.
8.5 .3 Derived classes
In the construct
aggr identifier : public0p, typedef-name
the typedef-name must dcnote a previously declared class, which is called a base class for the class
being declared. The latter is said to be derived from. the fonner. For the meaning of public see
§8.5.8. The membcrs of the base class can be referred to as if thcy were members of the derived
class itself, cxcept when a base member name bas been re-defined in the dcrived class; in this case
the typedef-name::iden:ljier notation (§7.1) can be used to refer to the hidden name. For example:
atruot base {
int a, b;
};
d.a • 1;
d. base : : b • 2;
d.b • 3;
d..c • 4;
assigns to the four members of d..
A derived class can itself be used as a base class. lt is not possible to derive from. a union
(§8.5.12). Assignment is not implicitly defined (see §7.14 and §14.1) for a objccts of a class
derived from. a class for which operator• ( ) bas becn defined (§8.S.10).
8.5.4 Virtual functions
If a base class base contains a virtual (§8.1) function vf, and a derived class d.erived. also
contains a function vf then a call of vf for an abject of class de:r:ived invokes de:r:ived: : vf.
For example:
struct base {
virtual void. vf();
void f();
} ;
derived d.;
base• bp • &.d;
bp->vf ();
bp->f ();
The calls invoke derived: :vf and base: :f, respectively for the class derived object named
d. That is, the interp.retation of the call of a virtua1 function depencis on the type of the object for
whicb it is called, whereas the interpretation of a call of a non-virtual member function depends
only on the type of the pointer denoting that object. This implies that the type of objects of classes
with virtual functions and abjects of classes derived from such classes can be determined at run
time.
C If a derived class bas a member of the same name as a virtual function in a base class the its type
must be the same in both classes. A virtual function cannot be a friend (§8.5.9). A function f
in a c:lass derived from a class which has a virtual fonction fis itself considered virtual. A virtua1
function in a base class must be defined. A virtual function which bas been ddined in a base class
nced not be defined in a derived class. ln that case, the function defined for the base class is used
in all œlls.
8.S .S Constructors
A me:mber function with the same name as its class is called a constructor. A consttuctOr has no
retum value type; it is used to construct values of its class type. A constructor can be used to
create new objects of its type, using the syntax
typedef-lllJ:IM ( argument-linopt )
When no constructor for class xis found which accepts the assigned type, no attempt is made to
find other constructors to convert the assigned value into a type which would be acceptable to a
constructor for class x. For example:
class X { X( int); } ;
class Y { Y{X); } ;
Y a• 1; I• illegal: Y(X(1)) not tried •I
operator int();
} ;
X a;
int i • int(a);
i • (int)a;
i • a;
ln all tbree cases the value assigned will be found by a ca1l of the function X: : operator int C) .
A user defined type conversion is implic:itly applied only if it is unique; see §8.9. Note that if a
class x bas a conversion to an integral or pointer type declared, an x can be used whereever an
expression of such a type is required. For example
X a, l:>;
(_ inti• (a)? 1+a: O;
int j • {a&&.l:>)? a+l:>: i;
8.S. 7 Destructors
A membcr fonction of class cl namcd ·cl is called a destructor. A destructor has no retutn
value and takes no arguments; it is used to destroy values of type cl immediatcly before the objeet
containing them is desuoyed. A destructor cannot be ov-erload or friend.
The destructor for a base class is exccutcd after the destructor for its derlvcd class. Destructors
for member abjects are executcd before the desttuctor for the objeet they are members of. See §17
for an explanation of how destructors can be used for free storqe management.
An abject of a class with a destructor cannot be the member of a union.
8.S .8 Visibility of member names
The members of a class declarcd with the keyword claaa are prlvate, that is, their names can
only be used by membcr fonctions (§8.5.2) and friends (see §8.5.10), unless they appear aftcr the
C++ Re/erence Manual 25
"public: n label; in that case they are public. A public member can be uscd in any function. A
struct is a class with an members public; see §8.5.11.
H the keyword public precedes the base class name in the declatation of a derived class the
public members of the base class are public for the derived class; if not, tbey arc private. A public
membcr mem of a private base class base can be declared to be public for the derived class by a
declaration of the form
typede/-1111.1n4 • identifier ;
whcre the typedef-name denotes the base class and the identifier is the name of a member of the
base class. Such a declaration must occ:ur in the public part of the dcrived class.
Consider
claas base {
int a;
public:
int b. c;
int bf();
int ef(derived.L};
The extema1 function ef canuse only the names c, e, and df. Bcing a me:mbcr of derived, the
function df canuse the names b, c, bf, d, e, and df, but nota. Being a me:mber of base, the
function bf canuse the mcmbers a, b, c, and bf.
8.S.9 Friends
A frlend of a class is a non-member function which may use the ptivate member names from the
class. A frlend is not in the scope of a class and is not called using the member selection syntu
(unless it itself is the membcr of some class). The following example illustrates the differences
between membcrs and frlends:
(_ class private {
int a;
friend void friend._set(private•, int);
public:
void mesnl>er_aet(int);
} ;
void friencLaet(pr:l.vate• p, inti) { p->a • i;}
(_ void private.member_aet(int i) {a• i; }
pri vate obj;
friend_set(Lobj,10);
obj.member_set(10);
C++ Reference Manual 26
When a friend declaration refers to an ovcrloaded name or opcrator only the function specified
by the argument types becomes a friend. A member of. a class c 11 can be the frlend of a class
cl2. For example
(_ claaa cl2 {
friend. char• cl1::foo(int);
};
Ail the functions of a class cl 1 can be made friends of a class c 12 by a single declaration
class cl2 {
friend. cl1
};
Placing the definition of a fri end function in a class declaration is a shorthand for declaring it
and tben defining it inline just as for mem.ber functions; see §8.5.2.
8.5 .10 Operator functions
Most operators can be overloaded to take class object operands.
operator-{unction-name:
operator operlUOr
optrator: one of
new delete
A
+
* /
"+• -·
L
"'•
<•
•
L•
>•
<
,.
L&.
>
<<
Il
>>
++
>>•
••
<<•
()
/•
••
[l
"·
I•
The last two operators are function call and subscrlpting. An operator function (exœpt operator
new() and operator delete( ); see 117) must eitber be a member function or take at least one
argument of class type. See also §7.16.
8.5 .11 Structures
A structure is a class witb all members public. That is
struct • { ••• };
is equivalent to
claas s { public: ••• };
A structure may have member functions (including constructors and desttuctors).
8.5.12 Unions
A union may be tbought of as a structure all of whose mem.ber abjects begin at offset O and whose
size is sufficient to contain any of its member objects. At most one of the member objects can be
stored in a union at any time. A union may have membcr functions (ineluding constructors and
destructors). It is not possible to de.rive a class from a union. An abject of a class with a
constructor or a destructor cannot be a member of a union.
A union of. the form
union { member-list } ;
is called an anonymous union; it defincs an unnamed object. The names of the members of an
C+ + Reference Ma.nuai 27
anon.ymous union must be distinct from other names in the scope where the union is declared; they
can be used directly in that scope without using the usual membcr access syntax (§8.S). For
example
union { int a; char• p; };
a• 1;
p • "asd.f";
Here a and p are used like ordinary (non-member) variables, but since they are union members
they have the same address.
8.5.13 Bit fields
( __ A member-declararor of the form
identifierop, : constant•upression
specifies a field; its length is set off from the field name by a colon. Fields are packed into
machine integers; they do not straddle words. A field which does not fit into the space remaining
in an integer is put into the next word. No field may be wider than a word. Fields are assigned
risht-to-left on some machines, left-to-rlght on other machines; see §2.6.
An unnamed field is useful for padding to conform to extemally-impoed layouts. As a special
case, an mmamed field with a width of Ospecifies alignment of the nm field at a word boundary.
Implementations are not required to support any but integer fields. Moreover, even int fields
may be considered to be unsigned. For these reasons, it is recomme.ndcd that fields be declared as
unsigned. The address-of operator & may not be applicd to thcm, so that there are no pointers
to fields.
Fields may not be union membcrs.
8.5 .14 Nested classes
A class may be declared within another class. ln this case, the scope of the name of the inner class
and its public na.mes is restricted to the enclosing class. Except for this restriction the inner class
could have been declared outside its enclosing class. Declaring a class within another does not
affect the rules for acœss to private members, nor does it place the member functions of the inner
class in the scope of the enclosing class. For example:
int x;
class encloae {
int x;
class inner {
int y;
f () { X • 1; }
} ;
g( inner*);
} ;
int inner;
enclose.g{inner* p) { ••• }
ln this example, the x in f refers to the x declared before class enclose. Sincey is a private
member of inner, c; can not use it. Si.nec c; is a member of enclose, names used in c; are
C++ Reference ManUD,/ 28
resolved in the scope of class enclose. Thereforc inne:r in the argument declaration for 9' refers
to the enclosed type inner, and Dot to the int.
(_ 8.6 lnitializati.on
A declarator may spccify an initial value for the identifier being declared. The initializer is
preœded by •, and consists of an expression or a list of values nested in braces.
initia/izer:
• expression
• { initializer-li.n }
• { initializer-lisi , }
( upr,ssion-li.n >
initializer-list:
expression
initializer-li.n • initiali:er-li.n
{ initializer-lisi }
All the expressions in an initializer for a static or enemal variable must be constant expressions,
which are described in §15, or expressions which reduce to the address of a previously declared
variable, possibly offset by a constant expression. Autom.atic or register variables may be
initialized by arbittary expressions involving constantst previously declared variables and functions.
Static and cxternal variables which are not initialized are guanmtced to start off as .O; automatic
and register variables which are not initialized are guaranteed to stan off as prbage.
\Vhen an initializer applies to a scalar (a pointer or an object of arithmetic type), it consists of a
single expression, perhaps in braces. The initial value of the object is taken from the expression;
the same conversions as for assignment are performed.
Note that sinœ < ) is not an initializer, ' 'X a C) ; ' ' is not the dcclatation of an object of class x,
but the declaration of a function taking no argument and returning an x.
8.6 .1 Initializer lists
\Vhen the declared variable is an aggregate (a class or an array) then the initializcr may consist of
a brace-enclosed, comma-separated list of initializers for the members of the aggregate, writtcm in
incrcasing subscript or member ordcr. If the array contains subaggregates, this rule applies
recursively to the members of the aggregate. If there are fewer initializers in the list than tbere
are members of the aggregate, then the aggregate is padded with O's.
Braces may be elided as follows. If the initializer begins with a lcft bracc, then the s1Jœetding
(_ comma-separated list of initializers initi.alizes the membcrs of the aggrcgate; it is erroneous for
there to be more initializers than members. If, however, the initializer does Dot. begin with a left
braœ, tben only eDough clements from the list are taken to account for the members of the
aggregate; any remaining members arc left to initialize the ncxt member of the agregate of which
the current aggregate is a part.
For example,
int xCl • { 1 1 3, 5 };
declares and initializes x as a 1-dimensional array which bas three members, since no size was
spec:ified and there are thrce initializers.
C++ Reference Manual 29
..
float y[4]C3] • {
{ 1' 3, s }
(
-- { 2, 4, 6 }
\__ . { 3, s. 7 } ,
} ;
is a completely-bracketed initialization: 1, 3, and S initialize the first row of the array y[ o],
namely y t OH oJ, y t OJt 1 J, and y t Olt 2 l. Likewise the next two Unes initialize y t 1 J and
y[ 2 J. The initializer ends early and therefore y[ 3 J is initialized with O. Precisdy the same
effect could have bcen achieved by
float yt4][3J • {
1, 3, s, 2, 4, 6, 3, 5, 7
} ;
The initializer for y begins with a left brace, but that for y [ o ] does not, therefore three dements
from the list are used. Likewise the next three are taken successively for y t 1 J and y[ 2 J• Also,
float y[4l[3J • {
{ 1 }, { 2 }, { 3 }, { 4}
};
initializes the first column of y (regarded as a two-dimensional array) and leaves the rest O.
8.6.2 Cass objects
An object with private mcmbers cannot be initialized by simple assignment to its members as
descrlbed above; neither can a union object. An abject of a class with a constructor must be
initialized. If a class bas a construetor which does not take arguments tbat constructor is used for
abjects which are not explicitly initialized.
The arsuments for a constructor can also be presented as a paremhesized list; this style must be
used when creatina objects on the frce store. For example:
struct complex {
float re, im;
complex(float r, float i) { re•r; im•i; }
complex(float r) { re•r; im•O; }
} ;
8.6.3 References
\Vhen a variable is declared to be a TL, that is "reference to type 'l'", it can be initialized either by
C a pointer to type T, or by an object of type 'l'. ln the latter case the address-of operator L will be
implicltly applied. For example:
inti;
intL r1 • i;
intL r2 • Li;
Both r 1 and r 2 will referenœ i.
lnitialization of a referenœ is ueated very differently from assignment toit. As descrlbed in §7.1 a
reference is implicitly dereferenced when used. For example
r1 • r2;
means copy the integer referenced by r2 into the integer referenœd by r 1.
A rc:ference must be initialized. Bccause of the implicit dereferencing the value of a referenœ
cannot be changed after initialization. A reference can therefore be thought of as a name of an
object.
The expression Lr 1 yields the addtess of the object refcnnœd by r 1. Thus to get a pointer pp to
denote the same abject as r1 one can wrlte pp•LJ:1.
If the initializer for a reference to type T is not an lvalue an object of type T will be created and
initiaJiz,-_,d wiih the initializer using the usual initialization rules. The addrcss of that object then
beeomes the value of the referenœ. 'Ibe lifetime of an abject created in this way is the scope in
which it is created. For eumple:
doubleL rr • 1 ;
is legal and tt will point to a double containing the value 1 • 0.
Refercnces are particularly useful as formal argument types.
8.6.4 Character arr~ys
A final abbrcviation allows a char array to be initialized by a string. In this case suc:œssive
characters of. the string initialize me members of the array. For esample,
char msg[] • nsyntax error on line Ka,n•;
shows a c:baracter array whœe members are initializcd with a string.
8.7 Type namcs
Sometimes (to specify type conversions explicitly, and as an argument of s:Lzeof or new) it is
desired to supply the name of a data type. This is acc:omplished usina a "type name," which in
essence is a declaration for an object of that type which omi.ts the name of the object.
type-name:
ryp,-sp,cifier abnract-declararor
aburact-declarator:
empty
* abmact-declarator
abnract-declarator ( argument-declaration-list )
aburact-declarator C consram-expnssionopt J
C abstract-decla:rator )
It is possible to identify uniquely the location in the abstract-declarator where the identifier would
appear if the construction were a declarator in a declaration. The named type is then the same as
the type of the hypothetical identifier. For example,
\
C+ + Reference Manual 31
int
int *
int •[3J
(~ int •()
int ( •) ()
name respectively the types "integer," "pointer to integer," "pointer to an array of three
integers," "function returning pointer to integer," and "pointer to function returning an integer."
8.8 Typedef
Declarations containing the decl-specijier typedef define identifiers which can be used later as if
they were type keywords naming fundamental or derived types.
(_
typedef-'fl/J'IM:
ideruifler
Within the scope of a declaration involving typedef, eacb identifier appearing as part of any
declarator therein becomes syntactically equivalent to the type keyword naming the type associated
with the identifier in the way dcscribed in §8.4. The name of a class or an enum is also a rypedef-
'fl/J'IM • For example, after
typedef int MILES, •ICLICICSP;
struct complex { double re. im; };
the constructions
MILES distance;
extern KLICKSP metricp;
complex z, •zp;
are all legal declarations; the type of distance is int, that of metricp is "pointer to int".
typed.ef does not inttoduce brand new types, only synonyms for types which could be specified in
another way. Thus in the example above distance is considered to have exactly the same type
as any other int abject.
A class declaration, however, does introduœ a new type. For eumple:
struct X { int a; };
atruct Y { int a;};
X a1;
y a.2;
int a3;
declares three variables of three diffcrent types.
A declaration of the form
name-declaration:
a,gr ùkntifer ;
enum identifier ;
specifies that an identifier is the name of some (possibly not yet defined) class or enumeration.
C Such declarations allows declaration of classes which refer to eacb other. For example:
C++ Reference Manual 32
class vector;
class matrix {
(_
friend matrix operator•(matrixL, vector&);
} ;
elass vector {
enum-li.st:
enumerator
,mum-lin , enumerator
enumerator:
identifier
identifier • connani-upression
The identîfiers in an enum-list are declared as constants, and may appear wherever constants are
required. If no enumerators with • appear, then the values of the corresponding constants begin at
0 and increase by 1 as the declaration is read from left-to-right. An enumerator with • gives the
associated identifier the value indiœted; subsequent identifiers continue the progression from the
assigned value.
The names of enumerators must be distinct from those of ordinary variables. The· names of
enumcrators with different CODStants must also be distinct. The values ot the enumerators need
not be distinct.
The role of the identifier in the enum-specifier is entircly analogous to that of the class name; it
names a particular enumeration. For example,
enum color { chartreuse, burgundy, claret•20, wine4ark }:
col• claret;
cp • &.col;
The meaning of an asm decl.aration is not defined. Typically it is used to pass information tbrough
the compiler to an assembler.
9. STATEMENTS
(_ Except as in~cated, statements are exccuted in sequenœ.
9.1 Expression statement
Most statements are expression statements, which have the form
expression ;
Usually expression statements are assig:nments or function calls.
C+ + Reference Manual 34
statement-lin:
statement
statement statement-list
Note that a declaration is an example of a statement (§9.15).
9.3 Conditional statemcnt
The two forms of the conditional statement are
if ( expression ) IUltement
if { expression ) natement elae na,ement
The expression must be of in'tegral or pointer type or of a class type for which a conversion to
integral or pointer type is defined (sec §8.5.6). The expression is evaluated and if it is non-zero,
the fint substatement is cxecuted. If else is used the second substatement is exccuted if the
expression is O. As usual the 0 else0 ambiguity is resolved by connecting an elee with the last
encountered else-less if.
9.4 While statemcnt
The while statement bas the form
while ( apression ) statement
The substatement is executed repeatedly so long as the value of the expression remains non-zero.
The test takes place before each e:xecution of the statement. The expression is handled as in a
conditional statement (§9.3).
9.5 Do statemcnt
The d.o statement bas the form
d.o staiement while C expression ) ;
The substatement is executed repeatedly until the value of the expression becomes zero. The test
takes place after each execution of the statement. The expression is handled as in a conditional
statement (§9 .3).
9.6 For stàtement
The for statement bas the form
for ( natement-1 apression-1 opt expression-2opt ) sttJlement-2
This statement is equivalent to
statement-1
wbil e ( expression-1 ) {
statement-2
expression-2 ;
}
Thus the first statement specifies initialization for the loop; the first expression speclfies a test,
made before each iteration, such that the loop is exited when the expression becomes O; the second
expression often specifies an incrementing that is performcd after each iteration.
C++ Reference Manual 35
Either or both of the expressions may be dropped. A missing expression-} makes the implied
while clause equivalent to while ( 1). Note that if statement-1 is a declaration, the scope of the
name dcclared extends to the end of the block enclosing the for-statement.
C 9. 7 Switch statement
Toc swi tch statement causes control to be transferred to one of several statements depending on
the value of an expression. It bas the form
swi tch ( expression ) statement
The type of the expression must be of integral or pointer type. Any statement within the statement
may be labeled with one or more case prefixes as follows:
( case constant-expression :
'---
where the constant expression must be of the samc type as the switch expression; the usual
arithmetic conversions are performed. No two of the case constants in the same switch may have
the same value. Constant expressions are defined in §15.
There may also be at most one statement prefix of the form
default:
When the switeh statement is executed, its expression is evaluated and compared with eacb case
constant. If one of the case constants is equal to the value of the expression, control is passed to
the statement following the matched case prefix. If no case constant matclles the expression, and if
there is a default prefix, control passes to the prefixed statement. If no case matches and if
there is no def aul t then none of the statements in the switch is executed.
case and def aul t prefixcs in thcmselves do not alter the flow of control, whicll continues
unimpeded across such prefixes. To exit from. a switch, sec break, §9.8.
Usually the statement that is the subject of a switch is compound. Declarations may appear at the
head of this statement, but initializations of automatic or register variables are ineffective.
9.8 Break statement
The statement
break;
causes termination of the smallest enclosing while, do, for, or switch statement; control passes
to the statemcnt following the terminated statement.
9.9 Continue statement
The statement
continue;
causes control to pass to the loop-continuation portion of the smallest enclosing while, do, or for
statement; that is to the end of the loop. More preclsely, in each of the statements
while ( •.• ) { do { for( ••• ) {
a continue is·equivalent to goto eontin. (Following the contin: is a null statement, 19.13.)
9.10 Return statement
A function retums toits caller by mcans of the return statement, which bas one of the forms
C+ + Reference Manual 36
return;
return a.pression
The fi.nt form can be uscd only in functions which does not retum a value, that is, a function with
the retum value type void. The second form can be used only in fonctions retuming a value; the
value of the expression is retumed to the caller of the function. If required, the expression is
converted, as in an initialization, to the type of the function in wlûch it appears. Flowing off the
end of a function is equivalent to a retum with no retumed value.
9.11 Goto statement
Control may be transferred unconditionally by means of the statement
goto identifier ;
The identifier must be a label (§9.12) located in the current fonction. lt is not possible to transfer
cœtrol past a declaration with an (implicit or explict) initializer.
9.12 Labeled statement
Any statement may be preceded by label prefixes of the form
identifier :
which serve to declare the identifier as a label. The only use of a label is as a target of a goto.
The scope of a label is the current function, excluding any sub-blocks in which the same identifier
bas been redeclared. See §4.l.
9.13 Null statement
The null statemcnt bas the form
A null statement is useful to carry a label just before the } of a compound statement or to supply a
null body to a looping statement such as while.
9.14 Deletc statement
The delete statement bas the form
del ete expression
The result of the expression must be a pointer. The object pointed to is deleted. That is, after the
delete statement the object cannot be assured to have a well de:fined value; see §17. The effect of
applying delete to a pointer not obtained from the new operator (§7.1) is unddined. However,
(_ deletin& a pointer with the value zero is harmless.
9.15 Declaration statement
A declaration statement is used to introduce a new identifier into a black; it has the form
declaration-staremtnt:
declaration
If an identifier introduœd by a declaration wcre previously declared, the outer declaration is
pushed down for the duration of the black, after which it resumes its force.
Any initializations of auto or register variables are performed cach time their t:kclaration-
statement is executed. lt is possible to transfêr into a block, but not in a way that causes
initializations not to be performed; see §9 .11. lnitializations of variables with storage class natic
(§4.2) are performed only once when the program begins execution.
C++ Reference Manual 37
Here int is the type-speclfier; max ( int a , int b, int c ) is the function-declarator; { • • • }
is the block giving the code for the statement.
Since in expression context an array name (in particular as an actual parameter) is taken to mean a
(_ pointer to the first element of the array, declarations of formal parameters declared "array of ••• "
are adjusted to read "pointer to ... ".
A base class initializer bas the form
bas,-class-inhializer:
: ( argument-li#Opt
lt is used to spccify arguments for a base class constructor in a consuuctor for a derived class. For
example:
struct base { baae(int); ••• };
struet d.erived: baae { d.eriTed.(int); };
der i ved d ( 10 ) ;
The base class's constructor is callcd for the object d. witb the argument 11.
C++ Refertnce Manual 38
14.2 Functions
There are only two things that can be done witb a function: call it, or take its add:ress. If the name
of a fun.ction appears in an expression not in the function-name position of a call, a pointer to the
function is generated. Thus, to pass one function to another, one might say
type4ef int (•PP)();
extern g(PP);
extern f();
g(f);
Then the defmition of g might read
g(PF funcp)
{
(* f uncp ) ( ) ;
}
Notice tbat f must be declared explicitly in the calling routine since its appearance in g cf) was
not followed by C•
14.3 Arrays, pointers, and subscripting
Every time an identifier of array type appears in an expression, it is convcned into a pointer to the
first member of the array. Because of this conversion, arrays are not !values. By definition, the
subscript operator [ J is interpreted in such a way tbat E 1 [ !2 J is identical to • C C11 >+ C12 ) ) .
Beœuse of the conversion rules which apply to +, if E 1 is an array and E2 an integer, thcn
E 1 rE2 l refen to the E2-th member of E 1. 'Iherefore, despite its asymmetric appcarance,
subscripting is a commutative operation.
A consistent rule is followed in the case of multi-dimensianal arrays. If E is an n-dimensional
array of rank i x j x · · · x k, then E appearing in an expression is converted to a pointer to an
(n -1 )-dimcnsional array with rank Jx · · · x k. If the * operator, either explicitly or ùnplicitly as
a result of subscripting, is applied to this pointer, the result is the pointed-to (n-1)-dimensional
array, which itself is immediately converted into a pointer.
For exam.ple, consider
int x[3][5J;
Here x is a 3 x 5 array of integers. When x appean in an expression, it is convened to a pointer
to (the fint of three) 5-membered arrays of integen. In the expression xt i J, which is equivalent
to * Cx+ i ) , x is first converted to a pointer as described; then 1 is eonvened to the type of x,
which involves multiplying i by the length the object to wbich the pointer points, namely 5 integer
objects. The results are added and indirection applied to yield an array (of 5 integen) which in
turn is converted to a pointer to the fim of the integen. If there is another subscrlpt the sam.e
argument applies again; this time the result is an integer.
It follows from all this that arrays in C++ are stored row-wise (last subscript varies fastest) and
that the first subscript in the dcclaration helps determine the amount of storage consumed by an
array but plays no other part in subscrlpt calculations.
14.4 Explicit pointer conversions
Certain conversions involving pointers are permitted but bave ùnplementation-dependent aspects.
They are all specified by means of an explicit type-conversion operator, §§7 .2 and 8.7.
C+ + Reference Manu.al 41
A pointer may be converted to any of the integral types large enough to hold it. 'Wbether an int
or long is required is machine depcndent. The mapping function is also machine dependent, but
is intended to be unsurprising to those who know the addressing structure of the machine. Details
C_ for some particular machines were given in §2.6.
An object of integral type may be explicitly converted to a pointer. The mapping always carries an
integer converted from a pointer back to the same pointer, but is otherwise machine dependent.
A pointer to one type may be converted to a pointer to another type. The resulting pointer may
cause addressing exceptions upon use if the subject pointer does not refer to an object suitably
aligned in storage. It is guaranteed that a pointer to an object of a given size may be converted to
a pointer to an object of a smaller size and back again without change. Different machines may
differ in the number of bits in pointers and in alignment requirements for objects. Aggregates are
aligned on the strictest boundary required by any of their constituents.
Some difficultics arise only when dubious coding practices are used. It is exceedingly unwise to
writc programs that dcpcnd on any of thesc propcrties.
C The ordcr of evaluation of function arguments is not specificd by the languagc. It is right-to-lcft
on somc machines lcft-to-right on othcrs. The ordcr in which sidc effects tak.e place is also
unspecificd.
Since charactcr constants arc rcally abjects of type int, multi-character charactcr constants may be
permitted. Toc specific implementation is very machine dependent, howevcr, because the order in
which characters arc assigncd to a word varies from one machine to anothcr. On some machines
fields are assigned left-to-right in a word, in othcrs right-to-lcft.
Toese differences are invisible to isolated programs which do not indulge in type punning (for
example, by converting an int pointer to a char pointer and inspecting the pointed-to storage),
but must be accounted for when conforming to externally-imposed storage layouts.
17. FREE·STORE
The new operator (§7.2) will call the function
extern void* operator new(lon;);
to obtain storage. The argument specifies the numbcr of bytes requircd. The store will be
uninitializcd. H operator newC ) cannot find the amount of store required it will return zero.
The delete operator will call the function
extern void operator delete(void*)i
to free the store pointed to for re-use. The effcct of c.alling operator delete C ) for a pointer not
obtained from operator new() is undefincd, and so is the effect of calling operator
del ete C) twice for the same pointer. However, deleting a pointer with the value zero is
harmless.
Default versions of operator new() and operator delete() are provided, but a user may
supply othcrs more suitable for parti.cular applications.
\Vhen a class object is created using the new operatot the constructor will (implicitly) use
operator newC) to obtain the store needed. By assigning to the thi• pointer before any use of
a member a constructor can implement its own storage allocation. By assigning a zero value to
tbis, a destructor can avoid the standard dcallocation operation for objects of its class. For
example:
class cl {
int v[ 10];
cl() { this • my_own_alloeator( sizeof(cl) ); }
·cl{) { my_own_deallocator( thia ); this • O; }
}
On entry into a constructor tbis is non-zero if allocation has already tak.en place (as is the case
for auto objects) and zero othcrwise.
If a derived class assigns to this, the call to its base class's constructor (if any) w:ill take place
after the assignment so that the base class constructor will refcr to the object allocated by the
derived class's constructor. Ha base class's constructor assigns to thia, the new value will also be
uscd by the dcrived class's constructor (if any).
18. SYNTAXSUMMAY
This summary of C+ + syntax is intendcd to be an aid to comprehension. lt is not an exact
statement of the language.
C+ + Reference ManUlll 43
18.1 Experessions
expression:
term
C expression binary-operator expression
expression ? expression : expression
expression-list
term:
primary
• term
& rerm
- term
1 term
• term
++ term
-- term
term ++
term --
< ryp.-nam, ) expression
simple-rype-na:me ( u.pression-ltst )
aizeof expression
sizeof ( type-nome
11ew type-name
new C rype-nam, )
primary:
id
: : identifier
cannant
string
thia
C upression )
primary [ expression ]
primary ( expression-Jinopt )
primary • id
primary - > id
id:
identifier
operaror-function-name
typedef-nam, : : tdenrijier
typedef-111l1M : : operaror-function-~
expression-list:
expression
expression-lin , expression
operator:
unary-operator
binary-operaror
special-operaror
free-store-operœor
Binary operators have preœd=nce decreasing as indicated:
C+ + Referenct Manua.l 44
binary-operator: one of
*
+
/
"
<< >>
C >
•• f•
&
A
ll
If
• +•
-· *· /• "• •• ,. >>• <<•
una:ry-operator: one of
* & ++
speciaJ.operator: one of
() [l
jree-store-operator: one of
new delete
type-name:
tkcl-sp,cijiers absrract.tüclarator
abstract-declarator:
m,,pty
• abstract-dtclarator
abstract-declarator ( argumenr-declaration-li&t )
abstract-declarator [ connanr-,xpreuionopt J
simple-rype-name:
typedef-name
char
short
int
long
unaigned
f'loat
double
void
typedef-name:
idtntlfler
18.2 Declarations
declaration:
tkcl-specifiersqpt declarator-linOJJI ;
name-declaration
asm-declaration
C+ + Reference Manual 45
nam.e-declaration:
aggr identifier ;
enum identifier ;
aggr:
claaa
at:ruct
union
asm-declaration:
asm ( string ) ;
decl-specifiers:
decl-sp,cifier decl-specijiersopt
decl-specijier:
ss-sp,dfter
type-sp,cifter
fct-specijier
f:riend.
typed.ef
rype-sp,cif~r
simple-rype-name
class-specijier
enum-speciji,r
conat
ss-specijier:
auto
exte:rn
:rec;iate:r
static
fct-specifler:
il'lline
ove:rload.
vi:rtual
declarator-list:
init-declarator
init-declaraior , declarator-list
init-declarator:
declarator initializeropt
declarator:
dname
C declarator )
* conat , declarator
&. constop, declarator
0
declarator ~ argument-declaration-list
declarator [ con.nant-upresslonopt l
C+ + Reference Man'Ulll 46
dname:
simplt-dnam.6
typedef-1111m1 • simple-dname
c_ simple-dname:
identifter
typedef·Nlm.6
• typede/-1111.lM
operaror-function-name
conversion-funclion-name
operaror-function-name:
operator operaror
conversion-function-name:
operator type
argument-declararion-list:
11rg-declaralion-listopt ••• opt
11rg-declaralion-list:
arg-declaration-llst , argument-declara:don
argument-declararion
11rgument-declaralion:
dec/-speciflers declararor
decl-specifters declararor • constant-expression
class-specljier:
class-head { member-lisr t }
class-head { member-lisr°:,, public : member-lisr0 pt }
class-h,ad:
aggr identijier 1
aggr identijier: , : publieopt typedef-nam11
member-list:
membu-declaralion member-listop,
member-declararion:
decl-speciflersont member-declarator initializer t
• .JJ:•. r
fu nction-u., •
1 ".itton ; opt
member-declararor:
declararor
identifteropt consrant-expression
initializtr:
• expression
• { initializer-lisr }
• { initializer•lisr , }
( upression•list )
C+ + Reference Manual 47
initializer-li.rt:
expression
initializer-list , initializer-list
{ initializer-list }
enum-specifier:
enum identifieropt { enum-list }
enum-list:
enumerator
enum-list , enumerator
(_ enumerator:
identifier
identifier• constant-expression
18.3 Statements
compound-statement:
{ st11.tement-listopt }
statement-list:
St/1.tement
sttztement statement-list
sttztement:
declaration
expression :
if ( expression ) statement
if ( expression ) statement else statement
whi le ( expression ) statement
do statemenr while ( expression ) ;
for ( statement expression01Jt ; exprusiono. t ) statement
swi tch ( expression ) statement "
case constant-expnssion : statemem
default : statement
break:
continue;
return expression t
goto identifier ; op
identifier : statement
(_ del ete expression
exterMl-definition:
function-definition
declaration
)
C++ Reference Manual 48
juncrion-definition:
decl-specifiersopt function-declarator base-class-initializeroptfunction-body
function-declarator:
declarator < argument-declaration-list )
function-body:
compound-statement
base-class-initializtr:
: ( argument-listopt
18.5 Preprocessor
#define identr'fier token-string
#define identifier ( identr'jier , •.• , identifier ) tolœn•string
#else
#end.if
#if expression
#ifdef identifier
#ifndef identifier
#include " fiœna.me "
#inelude < filenam, •
#line constant" filename"
#undej identifier
means
extern int f();
in both C++ and C.
Si.nœ clus names in C++ are in the sa.me nam.e spaœ as other names, constructs like
struct • { int a;} a;
atruct atat atat();
c:annot be used.
19.3 Anachronisms
A class name can be prefixed with the one of the keywords claaa, atruct, or union in the
declaration of class objects, pointers, etc. For example
atruet • a, •p;
atruct a f();
Programs using the old function definition syntax
C+ + Reference Manual 50
old-:function-deftnition:
decl-speciftersopt old..junction-declararor declaration-list function-body
old..junction-declarator:
declarator ( parameier-list )
paramerer-list:
identifier
identifier , identifttr
for example
max(a.b) { return (a<b)? b: a; }
may be used. H a function defined like this has not bee.n previously declared its argument type will
be taken to be C••• ) , that is, uncheckcd. If it bas been declared its type must agree with tbat of
the declaration.
(
Index
while (1) {
object• p • h->get();
printf("taak ka\n",n);
t•>put(p);
}
}
main()
{
qhead• hh • new qhead;
qtail• t . hh->t&il();
qbea«h h;
h • new qhead;
new pc(n,t,h);
printf("main()'• loop\n");
t • h•>tail C ) ;
}