Chapter 2 C++
Chapter 2 C++
Chapter 2 C++
BASICS OF C++
To understand the basic parts of a simple program in C++, let us have a look at the following code:
• Any C++ program file should be saved with file name extension “.CPP”. Type the program directly
into the editor, and save the file as hello.cpp, compile it and then run it. It will print the words Hello
World! On the computer screen.
• The first character is #. This character is a signal to the preprocessor. Each time you start your
compiler, the preprocessor runs through the program and looks for the pounds (#) symbols and act
on those lines before the compiler runs.
• The include instruction is a preprocessor instruction that directs the compiler to include a copy of
the file specified in the angle brackets in the source code.
• If the path of the file is not specified, the preprocessor looks for the file under c:\tc\include\ folder
or in include folder of the location where the editor is stored.
• The effects of line 1, i.e. include<iostream.h> is to include the file iostream.h into the program as if
the programmer had actually typed it.
• When the program starts, main() is called automatically. Every C++ program has a main() function.
The return value type for main() here is void, which means main function will not return a value to
the caller (which is the operating system).
• The main function can be made to return a value to the operating system. The Left French brace
“{“signals the beginning of the main function body and the corresponding Right French Brace “}”
signals the end of the main function body. Every Left French Brace needs to have a corresponding
Right French Brace.
1
• The lines we find between the braces are statements or said to be the body of the function.
• A statement is a computation step which may produce a value or interact with input and output
streams.
• The end of a single statement ends with semicolon (;).
• The statement in the above example causes the string “Hello World!” to be sent to the “cout”
stream, which will display it on the computer screen.
• Cin>>var1>>var2>>var3;
Here three different values will be entered for the three variables. The input should be separated
by a space, tab or newline for each variable.
2
2.3. Putting Comments on C++ Programs
A comment is a piece of descriptive text which explains some aspect of a program. Program comments
are text totally ignored by the compiler and are only intended to inform the reader how the source code
is working at any particular point in the program. C++ provides two types of comment delimiters:
• Single Line Comment: Anything after // {double forward slash} (until the end of the line on
which it appears) is considered a comment. Example
cout<<var1; //this line prints the value of var1
• Multiple Line Comment: Anything enclosed by the pair /* and */ is considered a comment.
Example
/*this is a kind of comment where Multiple lines
can be enclosed in one C++ program */
Comments should be used to enhance (not to hinder) the readability of a program. The following two
points, in particular, should be noted:
• A comment should be easier to read and understand than the code which it tries to explain. A
confusing or unnecessarily complex comment is worse than no comment at all.
• Over-use of comments can lead to even less readability. A program which contains so much
comment that you can hardly see the code can by no means be considered readable.
• Use of descriptive names for variables and other entities in a program, and proper indentation of
the code can reduce the need for using comments.
In general, a function is a block of code that performs one or more actions. Most functions are called,
or invoked, during the course of the program, which is after the program starts execution. Program
commands are executed line by line, in the order in which they appear in the source code, until a
function is reached. The program then branches off to execute the function. When the function finishes,
it returns control to the line of code immediately following the call to the function. Functions consist
of a header and body. The header, in turn is made up of the return type, the function name, and the
parameters to that function. The parameters to a function allow vales to be passed into the function.
A parameter is a declaration of the type of value that will be passed to the function; the actual value
passed by the calling function is called arguments. Lets consider the example below:
3
• Functions return either a value or void (i.e. they return nothing).
• A function that adds two integers might return the sum, and thus would be defined to return an
integer value. A function that just prints a message has nothing to return and would be declared to
return void.
• A function may return a value using a return statement; a return statement also causes the function
to exit.
• If there is no return statement at the end of a function, the function will automatically return void.
2.5.1. Variables.
4
2.5.1.1. Fundamental Variable types.
Several other variable types are built into C++. They can be conveniently classified as integer, floating-
point or character variables.
• Floating-point variable types can be expressed as fraction i.e. they are “real numbers”.
• Character variables hold a single byte. They are used to hold 256 different characters and symbols of
the ASCII and extended ASCII character sets.
• The type of variables used in C++ program are described in the next table, which lists the variable
type, how much room.
Data Types
• Signed integers are either negative or positive. Unsigned integers are always positive.
• Because both signed and unsigned integers require the same number of bytes, the largest number
(the magnitude) that can be stored in an unsigned integer is twice as the largest positive number that
can be stored in a signed integer. For example: Lets us have only 4 bits to represent numbers;
5
In the above example, in case of unsigned, since all the 4 bits can be used to represent the magnitude of
the number the maximum magnitude that can be represented will be 15 as shown in the example. If we
use signed, we can use the first bit to represent the sign where if the value of the first bit is 0 the number
is positive if the value is 1 the number is negative. In this case, we will be left with only three bits to
represent the magnitude of the number. Where the maximum magnitude will be 7.
6
Identifiers
A valid identifier is a sequence of one or more letters, digits or underlined symbols. The length of an
identifier is not limited.
• Neither space nor marked letters can be part of an identifier.
• Only letters, digits and underlined characters are valid.
• Variable identifiers should always begin with a letter or an underscore. They should NOT begin
with a digit.
• Keywords should not be used as names for identifiers.
• C++ is case sensitive. Small letter and capital letters are different for C++. Eg: variable Age is
not identical with variable age
2.5.1.4. Initializing Variables.
• When a variable is assigned a value at the time of declaration, it is called variable initialization.
• This is identical with declaring a variable and then assigning a value to the variable immediately
after declaration.
7
Local Variables: the scope of the local variable is limited to the code level or block within which they
are declared. In the following example, the integer data type num1 is accessible everywhere whereas z is
only accessible in the add function and num2 is accessible in main function. This means cout<<z; or any
statement involving z is only valid in add function.
Example:
• In C++ the scope of a local variable is given by the block in which it is declared.
• If it is declared within a function, it will be a variable with a function scope. If it is declared in a
loop, its scope will be only in the loop, etc.
• The “typedef” Keyword is used to define a data type by the programmer, as the user of a
programming language is a programmer.
• It is very difficult to write unsigned short int many times in your program if many variables need
such kind of declaration. C++ enables you to substitute an alias for such phrase by using the
keyword typedef, which stands for type definition. For example:
8
• Immediately after the second line, whenever the compiler encounters the word USHORT, it will
substitute it with “unsigned short int”.
2.5.1.9. Characters.
• Characters variables (type char) are typically one byte in size, enough to hold 256 different values. A
char can be represented as a small number (0 - 255).
• Char in C++ are represented as any value inside a single quote
• When the compiler finds such values (characters), it translates back the value to the ASCII values.
E.g. ‘a’ has a value 97 in ASCII.
In C++, there are some special characters used for formatting. These characters are as follows:
\n new line
\t tab
\b backspace
\” double quote
\’ single quote
\? Question mark
\\ backslash
9
2.5.2. Constants.
• A constant is any expression that has a fixed value. Like variables, constants are data storage
locations in the computer memory. But, constants, unlike variables their content cannot be changed
after the declaration.
Constants must be initialized when they are created by the program, and the programmer can’t
assign a new value to a constant later.
• C++ provides two types of constants: literal and symbolic constants.
• Literal constant: is a value typed directly into the program wherever it is needed.
E.g.: int num = 43;
43 is a literal constant in this statement:
• Symbolic constant: is a constant that is represented by a name, similar to that of a variable. But
unlike a variable, its value can’t be changed after initialization. E.g.:
Int studentPerClass =15; students = classes * studentPerClass;
studentPerClass is a symbolic constant having a value of 15.
And 15 is a literal constant directly typed in the program.
• In C++, we have two ways to declare a symbolic constant. These are using the #define and the const
keyword.
• Used to declare multiple integer constants using a single line with different features.
Enables programmers to define variables and restrict the value of that variable to a set of possible
values which are integer.
10
• The enum type cannot take any other data type than integer
• enum types can be used to set up collections of named integer constants. (The keyword enum is short
for ``enumerated''.)
• The traditional way of doing this was something like this:
#define SPRING 0
#define SUMMER 1
#define FALL 2
• An alternate approach using enum would be enum { SPRING, SUMMER, FALL, WINTER };
• You can declare COLOR to be an enumeration, and then you can define five possible values for
COLOR: RED, BLUE, GREEN, WHITE and BLACK.
E.g.: enum COLOR {RED,BLUE,GREEN,WHITE,BLACK};
• Every enumerated constant has an integer value. If the programmer does not specify otherwise, the
first constant will have the value 0, and the values for the remaining constants will count up from the
initial value by 1. thus in our previous example
RED=0, BLUE=1,
GREEN=3, WHITE=4 and BLACK=5
• But one can also assign different numbers for each.
E.g.: enum COLOR{RED=100,BLUE,GREEN=500,WHITE,BLACK}; Where RED will
have 100 and BLUE will have 101 while GREEN will have 500, WHITE 501 and BLACK
502.
• A computer provides RAM for storing executable program code as well as the data the program
manipulates.
• Memory can be thought of as a contiguous sequence of bits, each of which is capable of storing a
binary digit. Typically, the memory is divided into groups of 8 consecutive bits called bytes.
The bytes are sequentially addressed. Therefore, each byte can be uniquely identified by its address.
11
2.7. Expressions and Statements.
• In C++, a statement controls the sequence of execution, evaluates an expression, or does nothing (the
null statement).
• All C++ statements end with a semicolon.
E.g. x = a + b;
: The meaning is: assign the value of the sum of a and b to x.
• White spaces: white spaces characters (spaces, tabs, new lines) can’t be seen and generally ignored
in statements. White spaces should be used to make programs more readable and easier to maintain.
• Blocks: a block begins with an opening French brace ({) and ends with a closing French brace (}).
• Expressions: an expression is a computation which yields a value. It can also be viewed as any
statement that evaluates to a value (returns a value).
E.g.: the statement 3+2; returns the value 5 and thus is an expression.
Some examples of an expression.
E.g.1:
3.2 returns the value 3.2
PI float constant that returns the value 3.14 if the constant is defined
secondsPerMinute integer constant that returns 60 if the constant is
declared
E.g.2: complicated expressions:
x = a + b;
y = x = a + b;
The second line is evaluated in the following order:
1. Add a to b.
2. Assign the result of the expression a + b to x.
3. Assign the result of the assignment expression x = a + b to y.
12
2.8. Operators.
2.8.1.1. Compound assignment operators (+=, -=, *=, /=, %=, >>=, <<=, &=, ^=).
• Compound assignment operator is the combination of the assignment operator with other operators
like arithmetic and bit wise operators.
• The assignment operator has a number of variants, obtained by combining it with other operators.
E.g.:
value += increase; is equivalent to value = value + increase;
a -= 5; is equivalent to a = a – 5; a /= b; is equivalent to a = a / b;
price *= units + 1 is equivalent to price = price * (units + 1); And the
same is true for the rest.
13
• To obtain a real division when both operands are integers, you should cast one of the operands to be
real. E.g.: int cost = 100; Int volume = 80;
Double unitPrice = cost/(double)volume;
• The module(%) is an operator that gives the remainder of a division of two integer values. For
instance, 13 % 3 is calculated by integer dividing 13 by 3 to give an outcome of 4 and a remainder of
1; the result is therefore 1. E.g.:
a = 11 % 3 a is 2
• In order to evaluate a comparison between two expressions, we can use the relational operator.
• The result of a relational operator is a bool value that can only be true or false according to the result
of the comparison. E.g.:
(7 = = 5) would return false or returns 0 (5 > 4) would return true or returns 1
• The operands of a relational operator must evaluate to a number. Characters are valid operands since
they are represented by numeric values. For E.g.: ‘A’ < ‘F’ would return true or 1. it is like (65 <
70).
• Logical negation (!) is a unary operator, which negates the logical value of its operand. If its operand
is non zero, it produce 0, and if it is 0 it produce 1.
• Logical AND (&&) produces 0 if one or both of its operands evaluate to 0 otherwise it produces 1.
• Logical OR (||) produces 0 if both of its operands evaluate to 0 otherwise, it produces 1.
E.g.:
!20 //gives 0
10 && 5 //gives 1
10 || 5.5 //gives 1
10 && 0 // gives 0
N.B. In general, any non-zero value can be used to represent the logical true, whereas only zero
represents the logical false.
• The conditional operator takes three operands. It has the general form:
Syntax: operand1 ? operand2 : operand3
• First operand1 is a relational expression and will be evaluated. If the result of the evaluation is non
zero (which means TRUE), then operand2 will be the final result. Otherwise, operand3 is the final
result.
E.g.: General Example
Z=(X<Y? X : Y)
This expression means that if X is less than Y the value of X will be assigned to Z otherwise (if
X>=Y) the value of Y will be assigned to Z.
E.g.:
int m=1,n=2,min; min = (m < n ? m : n);
The value stored in min is 1. E.g.:
(7 = = 5 ? 4: 3) returns 3 since 7 is not equal to 5
• Multiple expressions can be combined into one expression using the comma operator.
• The comma operator takes two operands. Operand1, Operand2
• The comma operator can be used during multiple declaration, for the condition operator and for
function declaration, etc
• It first evaluates the left operand and then the right operand, and returns the value of the latter as the
final outcome. E.g. int m,n,min;
int mCount = 0, nCount = 0;
min = (m < n ? (mCount++ , m) : (nCount++ , n));
• Here, when m is less than n, mCount++ is evaluated and the value of m is stored in min. otherwise,
nCount++ is evaluated and the value of n is stored in min.
2.8.8. The sizeof() Operator
• This operator is used for calculating the size of any data item or type.
• It takes a single operand (e.g. 100) and returns the size of the specified entity in bytes.
The outcome is totally machine dependent. E.g.:
a = sizeof(char)
b = sizeof(int)
c = sizeof(1.55) etc
15
2.8.9. Explicit type casting operators.
• Type casting operators allows you to convert a datum of a given type to another data type. E.g.
int i; float f = 3.14;
E.g. a = = b + c * d.
c * d is evaluated first because * has a higher precedence than + and = =. The result
is then added to b because + has a higher precedence than = = And then == is
evaluated.
Precedence rules can be overridden by using brackets. E.g. rewriting
the above expression as:
a = = (b + c) * d causes + to be evaluated before *.
Operators with the same precedence level are evaluated in the order specified by the
column on the table of precedence rule.
E.g. a = b += c the evaluation order is right to left, so the first b += c is evaluated followed
by a = b.
16