Professional Documents
Culture Documents
Introduction to C++
1.1 Programming Languages and its Evolution
Computers are created to solve intricate mathematical problems. Though they may appear as
remarkably intelligent machines, they are not yet self-aware or cannot program themselves. These
computers need the direction of human beings in order to perform a specified task. These tasks are
known as programs and is accomplished through a step-by-step procedure known as algorithms. We
have all carried out an instruction using English or our own dialect as a medium of communication.
Well, computers tend to operate that way, except that it functions on a very strict grammatical rules
with no tolerance for ambiguity. Moreover, the step-by-step procedure must be in tedious detail so
that a given task may be accomplished as desired.
However since the computer would not directly understand these mnemonics, an assembler
is required to translate these mnemonics to its machine instruction counterpart.
1.1.3 High Level Language
The move from machine language to assembly language significantly made programming
much more convenient. However programmers were still directed to think in terms of
specific machine instructions. The big leap forward is making programming easier by
making it closer to natural languages (i.e. English). This idea made way for high level
languages such as Pascal, BASIC, FORTRAN, COBOL, C/C++ and Java. For example the
C++ code for solving z would be as follows:
z= x + y;
It would now be self-explanatory to understand this code given a little background in
arithmetic. But, similar to assembly language the computer would not execute this directly,
as a compiler is needed to convert a high level language instruction into machine language.
Even with its popularity, C wasn’t free from any inadequacy. Since C by itself is a contradiction
that is it can be regarded as a high-level language with low level language features. Most experts
agree that C is a middle level language and inherited the strengths and weakness of both
programming paradigm. For instance C has high-level language features that enable the
programmer to easily read and write assembly language programs. Yet, it can also directly
manipulate the computer’s memory similar to assembly language. Though this may be useful for
systems programming, but application programmers would find the learning curve quite steep.
Moreover automatic checks that is available to most high-level language is absent in C.
To address these issues, Bjarne Stroustrup still from AT&T Bell laboratories develop C++ in the
1980’s. He designed C++ as a subset of C and made C++ better than C. Since C++ is a subset of C
most C++ programmers aren’t considered as C programmers but C programmers can be considered
as C++programmers. The lacking features on C such as a facility for classes of object-oriented
programming and automatic checks were addressed in C++.
The C++ comment is a remark that is given by the programmer to identify or explain a
section of the code. The comments are ignored by the compiler. In C++ double slash (//)
indicates a single line comment while a slash-asterisk asterisk-slash (/* */) is used for
multiple line comments. During the early stages of your programming journey it is
recommended to write comments on critical parts of your code. For example in Listings 1
the placed on the topmost part of the program to describe what it does.
//your first C++ code of z = x + y equation
The preprocessor is a part of the program that provides the source file with the capabilities
provided from the included header file. On Listings 1 the invoke directive and header file
is:
#include <iostream>
This header would provide the features for your program to communicate from the outside
world (input) or to the outside world (output). Moreover the input/output in C++ involves
several definition from the iostream file, for instance cin is for input and cout for
output. There are many header files supported by C++ each supporting its own set of
facility. The traditional C heads must end with h extension, but modern C++ headers
reserved the h extension to old C headers. Instead header files on C++ removed the
headers for example <math.h> in C is now <cmath> in C++.
.
The namespace support is a new feature in C++ that is designed to simplify coding by
combining preexisting code from different vendors. For example Vendor1 and Vendor2
both have the function called abc(), since the compiler would not understand which
version the programmer mean, the namespace facility would guide the programmer to
which vendor s/he mean. So, Vendor1::abc() is the abc() function of Vendor1
consequently Vendor2::abc() is the abc() function of Vendor2.
The main() function is the entry point of your program. This constitute to a function
definition, which basically has two parts, the int main() is known as the function header
while the portion enclosed in curly braces ({ and })is the function body. The function
header summarizes the function’s interface with entire program while the function body
denote the instructions the must be executed by the computer. Each complete instruction is
called a statement, and each statement must end with a semicolon.
C++ differentiates uppercase and lowercase characters, in other words it is case sensitive.
So, the identifiers sample, SAMPLE, and Sample may have similar meaning but the
compiler considers these as three distinct identifiers. That is why it would create confusion
if you will try to create two variants of the same variable. A common practice would mix
the upper case with the lowercase by using the uppercase character to indicate a word
boundary (e.g. mySample, yourSample), this is otherwise known as camel case.
Reserved words are predefined names in C++ and the programmer is not allowed to use it
as names for variables (e.g. if() else). On most Integrated Development Environment
(IDE) the reserved words would appear with a different color. Keywords on the other hand
are not part of the core C++ language and are defined in headers (e.g. cin, cout). The
programmer may redefine its usage but confusion would arise since it would deviate from
its standard meaning. So to be safe, it is better use these keywords for their standard
purpose only.
Table 1: Some examples of correct and incorrect identifiers
All the operators can be applied to manipulate both integral and floating point data, except modulo
operator (i.e. modulo requires integers for it would get the remainder from a division process).
Moreover C++ uses precedence rules to address which operator is to be processed first. Normally,
algebraic precedence is followed, but when operators have the same precedence (e.g.
multiplication and division) C++ would look at the associativity. For operators acting on the same
operand with left-to-right associativity, the left operator would be evaluated first. Consequently for
right-to-left associativity, the right operator must be evaluated first. For example:
5 * 2 - 6 + 6 * 3 / 5 + 8;
If an integer would be expected as the result this means that:
(((5 * 2) – 6) + ((6 * 3) / 5)) + 8;
((10 – 6) + (18 / 5)) + 8; //evaluate *
((10 – 6) + 3) + 8; //evaluate / (note: this is integer
division)
(4 + 3) + 8; //evaluate –
7 + 8; //evaluate first +
15; //evaluate +
1.5.1 Evaluating Mixed Expression
It is obvious that integer expressions would yield to integer results while floating-point
results would produce floating-point results. But, a mixed expression are operands that has
different data types. To evaluate the mixed statement follow the rules below.
1. Before evaluation, an integer operand paired with a floating-point operand would be
changed to floating-point.
2. The entire expression are then evaluated corresponding to precedence and
associative rules.
For example:
3.4 * 3 - 5.6 + 4 / 2;
10.2 – 5.6 + 4 / 2; //evaluate 3.4 * 3.0 (rule 1)
10.2 – 5.6 + 2; //evaluate 4 / 2 (rule 2)
4.6 + 2; //evaluate 10.2 – 5.6 (same data type)
6.6 //evaluate 4.6 + 2.0 (rule 1)
static_cast<dataType>(expression);
Initially the expression is evaluated, then converted to a values specified by the data type.
So, if a floating-point data is casted as an integer, the number from right side of the decimal
place will be dropped. Conversely, a decimal place will be added if an integer would be
casted as a floating-point data.
float e = 2.71828;
static_cast<int>(e); // the output is 2
Finally, if larger-sized (e.g. long int) integral data type is converted to a smaller-sized (e.g.
short int) data type possible loss of data will occur since the content of the larger will not
be accommodated to the smaller. This principle is also true with the floating-point data
type.
You should include the <cmath> header in order to make use of these functions. When the
function is invoked the argument or parameter is the information that is passed to the
function and the result will be the return value. For example:
double root = sqrt (4);
This statement will extract the square root of the argument which is 4. Then the return
value is stored on the variable named root. Although a specific chapter (Chapter 3:
Modular Programming) is intended for this topic, an overview of function will provide an
outlook on how functions operate.