Chapter 2 Native Types and
Statements
tseaSnmt
?2.1 Program Elements
?2.1.1 Comments
?2.1.2 Keywords
?2.1.3 Identifiers
?2.1.4 Literals
?2.1.5 Operators and Punctuators
?2.2 Input/Output
?2.3 Program Structure
?2.4 Simple Types
?2.4.1 Initialization
?2.5 The Traditional Conversions
?2.6 Enumeration Types
?2.7 Expressions
?2.8 Statements
?2.8.1 Assignment and Expressions
?2.8.2 The Compound Statement
?2.8.3 The if
and if-else
Statements
?2.8.4 The while
Statement
?2.8.5 The for
Statement
?2.8.6 The do
Statement
?2.8.7 The break and continue
Statements
?2.8.8 The switch Statement
?2.8.9 The goto Statement
?2.9 Pragmatics
?Summary
?Exercises
Chapter 2 Native Types and
Statements
tseaSnmt
?This chapter will provide an introduction to
programming in C++ using its native types
n at i v e t y pe s
and its non-OOP features.
?A native type is a type provided by the
language directly.
?A traditional imperative language such as
Pascal or C. This is what we are calling the
kernel language.
ke r n e l an gu age .
?An important feature of OOP is typet
y pe -
extensibility.
e xt e n s i bi l i t y .
2.1 Program Elements
?A program is composed of elements called
tokens,
t oke n s ,
which are collections of characters
that form the basic vocabulary the compiler
recognizes.
?The character set includes:
?Lower- and uppercase alphabet: a b
?
z
A
?Z
?Digits: 0 1 2 3 4 5 6 7 8 9
.
?Operators: + * = . . . . . < .
?Punctuation: ; , ' . . . . ?
2.1 Program Elements
?Tokens can be interspersed with white space and
comment text inserted for readability and
documentation.
?There are five kinds of tokens:
?Keywords
?Identifiers
?Literals
?Operators
?and punctuators
?(see Section C.2,
"Lexical Elements," on page
406).
2.1.1 Comments
?In C++,
a multiline comment is written as
/* possibly
pos s i bl y
multiline
m u l t i l i n e
*/.
?C++
also has a single-line comment written
as // rest of line.
r e s t of l i n e .
2.1.2 Keywords
?Keywords
K e y w or ds
are explicitly reserved words that
have a strict meaning in C++.
?words used for type declarations: int
, char,
and
float;
?words used for statement syntax: do, for,
and if
?words used for access control: pub1i
c,
protected,
and private.
2.1.2 Keywords
2.1.3 Identifiers
?An identifier is a sequence of letters, digits,
and underscores.
?An identifier cannot begin with a digit.
Upper- and lowercase letters are treated as
distinct.
?While in principle, identifiers can be
arbitrarily long, many systems will
distinguish only up to the first 3 1
characters.
2.1.3 Identifiers
?Identifiers sample:
2.1.3 Identifiers
?Illegal Identifiers sample:
2.1.3 Identifiers
2.1.4 Literals
?Literals are constant values.
?There are literals for each C++ native data
types, including characters, booleans,
integers, floating-point numbers, and
pointers.
?String literals are also allowed.
2.1.4 Literals
?Literal samples:
2.1.4 Literals
?The character literals are usually given as
'symbol'.
2.1.4 Literals
?Some nonprinting and special characters,
such as blank or newline, require an escape
sequence, as shown in Table 2.8.
2.1.4 Literals
?String literals are stored as a series of
characters terminated with the null
character, whose value is 0. String literals
are static char[ ] constants. The character '"'
can be represented inside strings by
escaping it with the backslash character /.
2.1.4 Literals
?Floating-point literals can be specified
either with or without signed integer
exponents, as illustrated by Table 2.9.
2.1.5 Operators and Punctuators
?C++ gives special meaning to many
characters and character sequences,
illustrated in Table 2.10.
2.1.5 Operators and Punctuators
?Operators are used in expressions and are
meaningful when given appropriate
arguments.
?Punctuators
P u n c t u at or s
include parentheses, braces,
commas, and colons, and are used to
structure elements of a program.
?Operators, punctuators, and white space
serve to separate language elements.
2.2 Input/Output
?Input/output is not directly a part of the
language. It is added as a set of types and
routines found in a standard library.
?The iostream
i os t r e am
library overloads the two bitshift
operators.
2.2 Input/Output
?C++ input/output is not directly part of the
language but rather is added as a set of types and
routines found in a standard library. The C++
standard I/O library is iostream or iostream.h. The
file name without the .h extension is the official
ANSI standard name.
?Officially, the ANSI standard libraries that are
taken from C libraries are c followed by their
names without the .h extension. The ANSI C
standard library stdio.h can be used as the ANSI
C++ library cstdio.
2.2 Input/Output
?The iostream library overloads the two bitshift
operators.
?<< // "put to" output stream, normally left shift
?>> // "get from" input stream, normally right shift
?This library also declares three standard
streams:
?cout //standard out
?cin //standard in
?cerr //standard error
?Demo on page 29: io.cpp
2.3 Program Structure
?A program
A pr ogr am
in C++
C +
is a collection of
functions and declarations.
?Demo on page 30: gcd.cpp
?C++ relies on an external standard library to
provide input/output.
?C++ relies on an external standard library to
provide assertion testing.
2.3 Program Structure
?C++ uses a preprocessor to handle a set of
directives,
?A C++ program consists of declarations that
may be in different files.
?The function main()
is used as the starting
point for execution of the program.
2.3 Program Structure
?The assert
macro tests a condition for
correctness, and terminates the program if
the test fails.
?C++ compilers can compile multifile
programs.
CC module 1 .c module2.c my-
C m odu l e 1 . c m odu l e 2. c m y -
main.c
m ai n . c
2.4 Simple Types
?The simple native types in C++ are bool, int,
double, char, and wchar_t.
?bool
and the wchar_t types are new to C++
and are not in C and early C++ systems.
?The bool type provides a native boolean
type, and wchar_t provides a wide character
type, used for representing character sets
requiring more than the standard 255
characters.
2.4 Simple Types
?C++ integral simple types can often be
modified by the keywords short, long,
signed, and unsigned, to yield further
simple types.
?The floating-point types are float, double,
and long double.
2.4 Simple Types
?On most machines a bool or char is stored
in 1 byte. On many PCs an int is stored in 2
bytes, while 1ong, float , and double are all
stored in 4 bytes.
?C++ also has the sizeof operator, which is
used to determine the number of bytes a
particular object or type requires for
storage.
2.4 Simple Types
2.4 Simple Types
?The range of integral values that can be
represented on your system is defined in the
standard header file limits. Some examples
from our system are shown in Table 2.12.
2.4 Simple Types
?The range of floating-point values that can
be represented on your system is defined in
the standard header file float. Some
examples from our system are illustrated in
Table 2.13.
2.4 Simple Types
?The C++ standard library file limits contains
the template numeric_limits, which allows
the user to query the system about
characteristics of different types. For
example:
cout<< numeric_limits<int>::max()
<< 搃s the max of int.?
2.4.1 Initialization
?A variable declaration
de c l ar at i on
associates a type
with a variable name.
?Demo on page 33: circle1.cpp
?The variables are declared and defined inside
main() . Informally, we think of the definition
as creating the object.
?A definition can also initialize the value of the
variable.
2.4.1 Initialization
?Initialization can involve an arbitrary
expression,
?Initialization makes the code more readable,
less error prone, and more efficient.
2.5 The Traditional Conversions
?if x
and y are of different types, then x
+ y
is a mixed
expression.
e xpr e s i on .
?Automatic Expression Conversion x op y
x op y
1. Any bool, char, short, or enum is promoted to i
n t . Integral types that cannot be represented
as i n t are promoted to unsigned.
2. If, after the first step, the expression is of
mixed type, then, according to the hierarchy of
types,
2.5 The Traditional Conversions
?the operand of lower type is promoted to
that of the higher type, and the value of the
expression has that type.
?int < unsigned < long < unsigned long < f l
o a t < double < long double
2.5 The Traditional Conversions
?An automatic conversion can occur with an
assignment.
?A promotion,
or widening,
such as d
= i,
will usually be well behaved, but a
demotion,
or narrowing,
such as i
= d,
can
lose information.
?Eexplicit conversions called casts.
If i is an
i nt
,
then
2.5 The Traditional Conversions
static_cast<double>(i)
?will cast the value of i so that the
expression has type double.
?The static_cast
itsc_is available for a
conversion that is well defined, portable,
and invertible.
2.5 The Traditional Conversions
?Casts that are representation- or systemdependent
use reinterpret_cast
:
?i
= reinterpret_cast
<
int
>(&x) //system-dependent
?Two other special casts exist in C++: const_cast
and dynamic_cast
.
?The const
modifier means a variable's value is
non-modifiable.
?Older C++ systems allow an unrestricted form of
cast with the following forms:
( type) expression or type (expression)
2.5 The Traditional Conversions
?Demo on page 37: m_to_k.cpp
?Where the inline keyword modifies a function
definition, it suggests to the compiler that
when invoked, the code defining it avoid
function call, by being compiled inline.
2.6 Enumeration Types
?The keyword enum is used to declare a
distinct integer type with a set of named
integer constants called enumerators.
e n u m e r at or s .
enum suit {clubs, diamonds, hearts, spades };
?In C++, the identifier s u i t is now its own
unique type distinct from other integer
types. This identifier is called tag
t ag
name.
n am e .
2.6 Enumeration Types
?Enumerators can be defined and initialized
to arbitrary integer constants.
enum ages { laura = 7, i r a , harold = 59,
philip = harold + 7 };
2.6 Enumeration Types
?Demo on page 39: enum_tst.cpp
?Enumerators can be declared anonymously
an on y m ou s l y
without a tag name.
?enum { LB = 0, UB
= 99 };
?enum { lazy, hazy, crazy }why;
2.7 Expressions
?C++ has a variety of operators and
expression forms.
?assignment expression
?arithmetic expression
?toward mixing types and automatic conversions
2.7 Expressions
?Relational, Equality, and logical expression
2.7 Expressions
?Comma operator
expr1 , expr2
?conditional operator ?:
expr1?expr2:expr3
?The parentheses are not necessary because
the conditional operator has precedence
over the assignment operator.
?They operate on the machine-dependent bit
representation of integral operands.
2.7 Expressions
2.7 Expressions
?C++ considers function call
f u n c t i on c al l
() and indexing
i n de xi n g
or subscripting
s u bs c r i pt i n g
[] to be operators. It also has
an address
addr e s
& operation and an indirection
i n di r e c t i on
*
or dereferencing
de r e f e r e n c i n g
operation.
?C++ also has a sizeof
operator. It is
important to obtaining an appropriate
amount of storage for dynamically allocated
objects.
2.7 Expressions
2.7 Expressions
2.8 Statements
?C++
has a large variety of statement types.
It uses the semicolon as a statement
terminator.
2.8.1 Assignment and Expressions
?The left-hand side must be an lvalue. An
lvalue is a location in memory where a
value can be stored or retrieved. Simple
variables are lvalues.
?C++ expressions can be guaranteed by
using either the comma operator or
statement termination.
2.8.1 Assignment and Expressions
?C++
allows multiple assignments in a single
statement.
?C++
provides assignment operators that
combine an assignment and some other
operator.
?C++
also provides autoincrement (++) and
autodecrement (--) operators in both prefix
and postfix form.
2.8.1 Assignment and Expressions
?The postfix form behaves differently than
the prefix form by changing the affected
lvalue after the rest of the expression is
evaluated.
?Demo on page 45: auto.cpp
?The null statement is written as a single
semicolon.
?Usually a null statement is used where a
statement is required syntactically, but no
action is desired.
2.8.2 The Compound Statement
?A compound statement in C++ is a series of
statements surrounded by the braces { and
}.
The chief use of the compound statement
is to group statements into an executable
unit.
?In C, when declarations come at the
beginning of a compound statement, the
statement is called a block.
bl oc k.
2.8.3 The if
i f
and if-else
Statements
?The general form of an if statement is
if (condition)
statement
if (condition)
statement1
else
statement2
?Demo on page 46 if_test.cpp
2.8.4 The while
w h i l e
Statement
?The general form of a whi1e statement is:
while (condition)
statement
?Demo on page 47: while_t.cpp
2.8.5 The for
f or
Statement
?The general form of a for statement is
for (for-init-statement condition
( f or - i n i t - s t at e m e n t c on di t i on
; expression)
e xpr e s i on )
statement
s t at e m e n t
next statement
n e xt s t at e m e n t
?Demo on page 47: for_test.cpp
2.8.6 The do
do
Statement
?the general form is
do
statement
s t at e m e n t
while (condition)
( c on di t i on )
;
next statement
n e xt s t at e m e n t
?Demo on page 49: do_test.cpp
2.8.7 The break and continue
Statements
?To interrupt the normal flow of control within a
loop, the programmer can use the two special
statements
?break;
?continue ;
?The break statement, in addition to its use in
loops, can also be used in a switch statement.
?The continue statement causes the current iteration
of a loop to stop and the next iteration of the loop
to begin immediately.
2.8.8 The switch Statement
?The general form of the switch statement is
given by
switch (condition)
statement
?Demo on page 51: switch_t.cpp
2.8.8 The switch Statement
?The Effect of a switch
iftsceaohETw 1. Evaluate the integral expression in the
parentheses following switch.
2. Execute the case label having a constant value
that matches the value of the expression found
in step 1; if no match is found, execute the
default label; if there is no default label,
terminate the switch.
3. Terminate the switch when a break statement
is encountered, or by "falling off the end."
2.8.9 The goto Statement
?goto statement general form:
goto label;
?Demo on page 52: goto_tst.cpp
2.9 Pragmatics
?Tips 1
2.9 Pragmatics
?Tips 2
2.9 Pragmatics
?Tips 3
?Avoid casting, but where it is necessary use
the new-style safe casts such as
static_cast
itsc_<>.
?The use of const
and inline
is to be strongly
preferred to the use of "equivalent" define
macros.
Summary
?1. A
C++ program consists of declarations
that may be in different files.
?2.
The function main
() is used as the
starting point for execution of the program.
Summary
?3. C++ uses a preprocessor to handle a set
of directives, such as the include directive,
to convert the program from its
preprocessing form to pure C++ syntax.
?4. C++ relies on an external standard library
to provide input/output.
?5. The required simple types in C++ are
bool, double, i n t , char, and wchar_t.
Summary
?6. C++ has a large variety of statement
types. It uses the semicolon as a statement
terminator.
?7. The general form of an i f statement
?8. The general form of a while statement
Summary
?9. To interrupt normal flow of control
within a loop
?10. The goto statement is the most primitive
method of interrupting ordinary control
flow.
Chapter 2 Native Types and Statements
原创
©著作权归作者所有:来自51CTO博客作者luozhuang的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Chapter 6 : Control Statements : Looping
sas
C语言 学习笔记 C Primer Plus 学习 C -
CCNA 2 chapter
还请高手多多指教,有很多不是太明白的地方。
职场 ICMP 休闲