1 Introduction
1 Introduction
INTRODUCTION
Brief history Of C++
In 1971 Dennis Ritchie at Bell Labs extended the B language (by adding types) into
what he called NB, for "New B". Ritchie credits some of his changes to language
constructs found in Algol68, although he states "although it [the type scheme], perhaps,
did not emerge in a form that Algol's adherents would approve of" After restructuring the
language and rewriting the compiler for B, Ritchie gave his new language a name: "C".
In 1983, with various versions of C floating around the computer world, ANSI
established a committee that eventually published a standard for C in 1989.
In 1983 Bjarne Stroustrup at Bell Labs created C++. C++ was designed for the UNIX
system environment, it represents an enhancement of the C programming language and
enables programmers to improve the quality of code produced, thus making reusable code
easier to write.
C++ is not the best language to use in every instance. C++ is a great choice in most
instances, but some special circumstances would be better suited to another language.
Listing 1.1
1 #include <iostream.h>
Dialog 1.1 shows how the program in Listing 1.1 is compiled and run in a
typical UNIX environment. User input appears in bold and system response
in plain. The UNIX command line prompt appears as a dollar symbol ($).
Dialog 1.1
1 $ CC hello.cc
2 $ a.out
3 Hello World
4 $
Dialog 1.2
1 $ CC hello.cc -o hello
2 $ hello
3 Hello World
4 $
Execut-
LINKER able
Variables
Listing 1.2
1 #include <iostream.h>
6 workDays = 5;
7 workHours = 7.5;
8 payRate = 38.55;
9 weeklyPay = workDays * workHours * payRate;
10 cout << "Weekly Pay = ";
11 cout << weeklyPay;
12 cout << '\n';
13 }
4 This line defines an int (integer) variable called workDays, which will
represent the number of working days in a week. As a general rule, a
variable is defined by specifying its type first, followed by the variable
name, followed by a semicolon.
5 This line defines three float (real) variables which, respectively,
represent the work hours per day, the hourly pay rate, and the weekly pay.
As illustrated by this line, multiple variables of the same type can be
defined at once by separating them with commas.
6 This line is an assignment statement. It assigns the value 5 to the
variable workDays. Therefore, after this statement is executed, workDays
denotes the value 5.
7 This line assigns the value 7.5 to the variable workHours.
8 This line assigns the value 38.55 to the variable payRate.
9 This line calculates the weekly pay as the product of workDays,
workHours, and payRate (* is the multiplication operator). The resulting
value is stored in weeklyPay.
10-12 These lines output three items in sequence: the string "Weekly Pay
= ", the value of the variable weeklyPay, and a newline character.
When run, the program will produce the following output:
Weekly Pay = 1445.625
Listing 1.3
1 #include <iostream.h>
The most common way in which a program communicates with the outside
world is through simple, character-oriented Input/Output (IO) operations. C++
provides two useful operators for this purpose: >> for input and << for output.
We have already seen examples of output using <<. Listing 1.4 also illustrates
the use of >> for input.
Listing 1.4
1 #include <iostream.h>
7 This line outputs the prompt What is the hourly pay rate? to seek
user input.
8 This line reads the input value typed by the user and copies it to payRate.
The input operator >> takes an input stream as its left operand (cin is
the standard C++ input stream which corresponds to data entered via the
keyboard) and a variable (to which the input data is copied) as its right
operand.
9-13 The rest of the program is as before.
When run, the program will produce the following output (user input appears
in bold):
What is the hourly pay rate? 33.55
Weekly Pay = 1258.125
Both << and >> return their left operand as their result, enabling multiple
input or multiple output operations to be combined into one statement. This is
illustrated by Listing 1.5 which now allows the input of both the daily work
hours and the hourly pay rate.
Listing 1.5
1 #include <iostream.h>
6 cout << "What are the work hours and the hourly pay rate? ";
7 cin >> workHours >> payRate;
7 This line reads two input values typed by the user and copies them to
workHours and payRate, respectively. The two values should be
separated by white space (i.e., one or more space or tab characters). This
statement is equivalent to:
(cin >> workHours) >> payRate;
Because the result of >> is its left operand, (cin >> workHours)
evaluates to cin which is then used as the left operand of the next >>
operator.
9 This line is the result of combining lines 10-12 from Listing 1.4. It
outputs "Weekly Pay = ", followed by the value of weeklyPay, followed
by a newline character. This statement is equivalent to:
((cout << "Weekly Pay = ") << weeklyPay) << '\n';
Because the result of << is its left operand, (cout << "Weekly Pay = ")
evaluates to cout which is then used as the left operand of the next <<
operator, etc.
When run, the program will produce the following output:
What are the work hours and the hourly pay rate? 7.5 33.55
Weekly Pay = 1258.125
Comments
Listing 1.6
1 #include <iostream.h>
1 1 0 1 0 0 0 1
Bit
The C++ compiler generates executable code which maps data entities to
memory locations. For example, the variable definition
int salary = 65000;
causes the compiler to allocate a few bytes to represent salary. The exact
number of bytes allocated and the method used for the binary representation
of the integer depends on the specific C++ implementation, but let us say two
bytes encoded as a 2’s complement integer. The compiler uses the address of
the first byte at which salary is allocated to refer to it. The above assignment
causes the value 65000 to be stored as a 2’s complement integer in the two
bytes allocated (see Figure 1.3).
92 // decimal
0134 // equivalent octal
0x5C // equivalent hexadecimal
Real Numbers
A real variable may be defined to be of type float or double. The latter uses
more bytes and therefore offers a greater range and accuracy for representing
real numbers. For example, on the author’s PC, a float uses 4 and a double
uses 8 bytes.
float interestRate = 0.06;
double pi = 3.141592654;
In addition to the decimal notation used so far, literal reals may also be
expressed in scientific notation. For example, 0.002164 may be written in the
scientific notation as:
2.164E-3 or 2.164e-3
The letter E (or e) stands for exponent. The scientific notation is interpreted
as follows:
2.164E-3 = 2.164 × 10-3
Characters
Single and double quotes and the backslash character can also use the escape
notation:
'\'' // single quote (')
'\"' // double quote (")
'\\' // backslash (\)
Literal characters may also be specified using their numeric code value.
The general escape sequence \ooo (i.e., a backslash followed by up to three
octal digits) is used for this purpose. For example (assuming ASCII):
'\12' // newline (decimal code = 10)
'\11' // horizontal tab (decimal code = 9)
'\101' // 'A' (decimal code = 65)
'\0' // null (decimal code = 0)
Strings
Figure 1.4 illustrates how the string variable str and the string "HELLO"
might appear in memory.
A long string may extend beyond a single line, in which case each of the
preceding lines should be terminated by a backslash. For example:
"Example to show \
the use of backslash for \
writing a long string"
The backslash in this context means that the rest of the string is continued on
the next line. The above string is equivalent to the single line string:
"Example to show the use of backslash for writing a long string"
Programming languages use names to refer to the various entities that make
up a program. We have already seen examples of an important category of
such names (i.e., variable names). Other categories include: function names,
type names, and macro names, which will be described later in this book.
Names are a programming convenience, which allow the programmer to
organize what would otherwise be quantities of plain data into a meaningful
and human-readable collection. As a result, no trace of a name is left in the
final executable code generated by a compiler. For example, a temperature
variable eventually becomes a few bytes of memory which is referred to by
the executable code by its address, not its name.
C++ imposes the following rules for creating valid names (also called
identifiers). A name should consist of one or more characters, each of which
may be a letter (i.e., 'A'-'Z' and 'a'-'z'), a digit (i.e., '0'-'9'), or an underscore
character ('_'), except that the first character may not be a digit. Upper and
lower case letters are distinct. For example:
salary // valid identifier
salary2 // valid identifier
2salary // invalid identifier (begins with a digit)
_salary // valid identifier
Salary // valid but distinct from salary