You are on page 1of 32

eÁw

CHAPTER 7
Introduction to C++

OBJECTIVES
To Understand the basic features of C++ as a OPP language/

145
146
Introduction to C++

7.1 Introduction and History


Until
eÁw 1980, C programming was widely popular, and slowly people started realizing the
drawbacks of this language and at the same time, the engineers had come up with a new programming
approach that was Object Oriented programming. This approach of programming was capable enough to
overcome the previous drawbacks. Using this concept, Bjarne Stroustrup developed C++at AT & T Bell
Laboratories in Murray Hill, New Jersey. He developed this language in early 1980’s and was very much
concerned in making C++ more efficient. He based C++on C because C was much suitable to system
programming, and was widely available. He has also based C++ on another OOP featured language
called Simula67.
C++ is a superset of C because, any valid C program is a valid C++ program too but the vice versa
is not true. This can be clearly understood when we look at the fig7.1where we can understand there
relationship between C and C++. C++ can make use of existing C software libraries with major addition
of ‘class construct’. Therefore, the C++ programmers not only make use of the new features but also
have the privilege of using the traditional C features.
In the early stages, this language was called ‘C with classes’ and later in 1983, it was named
‘C++’ by Rick Mascitti. The ++ comes from the increment operator ++ which means C++ is an augmented
version of C. Finally C++ obtained anew outlook in the year 1997 when the ANSI/ISO standards
committee standardized the language by adding new features to it.

Figure 7.1 OOPs features

7.2 Characteristics of C++


C++ has certain characteristics over other programming languages. It provides huge
Function Library, that’s why its popularity is increasing day by day and more programmers are inclining
towards C++ due to its multiple features. The most remarkable ones are:
 Object-oriented programming: The possibility to orient programming to objects allows the
programmer to design applications from a point of view more like a communication between
objects rather than on a structured sequence of code. In addition it allows a greater reusability of
code in a more logical and productive way.

147
Introduction to C++

 Portability: We can practically compile the same C++ code in almost any type of computer
and operating system without making any changes. C++ is the most used and ported programming
language in the world.
 Brevity: Code written in C++ is very short in comparison with other languages, since the use of
special characters is preferred to key words, saving some effort to the programmer (and
prolonging the life of our keyboards!).
 Modular programming: An application’s body in C++ can be made up of several source code
files that are compiled separately and then linked together saving time, since it is not necessary to
recompile the complete application when making a single change, but only in the file that contains
it. In addition, this characteristic allows to link C++ code with code produced in other languages,
such as Assembler or C.
 C Compatibility: C++ is backward compatible with the C language. Any code written in C can
easily be included in a C++ program without making any change.
 Speed: The resulting code from a C++ compilation is very efficient due to its duality as high-
level and low-level language and to the reduced size of the language itself.
 Machine independent: It is a Machine Independent Language.
 Flexibility: It is highly flexible language with Versatility.
 Wide range of library functions: It has huge Library Functions which in turn reduces the code
development time and also reduces cost of software development.
 System Software development: It can be used for developing System Software viz., operating
systems, compilers, editors and data bases.

7.3 C++ character set and tokens


Character set means the valid set of characters that a language recognizes. The character set includes
letters, digits or any other sign. The following are the character set in C++.
Digits : 0 -9
Alphabets : a – z (lowercase alphabets) and A – Z (uppercase alphabets)
Special characters : + - / { } ( )% “ ? : != * blank space \ |& (these are some
Of characters which are the building blocks and they form the basic
program elements).
However, C++ is designed in such a way that it is capable of processing any of the 256 ASCII
characters as data or as literals.

A token is a smallest individual unit in a program or a lexical unit.

The most fundamental elements of a C++ program are “tokens” or lexical elements. These elements
help us to construct statements, definitions, declarations, and so on, which in turn helps us to construct

148
Introduction to C++

complete programs. Indeed, all the programming languages are made up of these individual syntax ele-
ments called
eÁw
tokens .C++ has following tokens.
 Identifiers
 Keywords
 Constants or Literals
 Punctuators
 Operators

7.3.1 Identifiers

An identifier is a name given to the programming elements such as variables, arrays, functions etc. It can
contain letter, digits and underscore. C++ is case sensitive and henceforth it treats uppercase and
lowercase characters differently.

Identifiers are the names given to program elements (program elements include variables, arrays,
functions, etc.). It is important to note that C++ is case sensitive and it treats uppercase and lowercase
characters differently. The following are some of the valid identifiers in C++.
Student _amount marks1 total_ score
STUDENT _AMOUNT RANK5 _Ad12
The following are some of the invalid identifiers:
34data - starts with a digit
reg-no - contains a special character ‘-‘
public - reserved word
Therefore, we can summarize the rules for naming an identifier as

 Identifiers are a sequence of characters which should begin with the alphabet either from
A-Z (uppercase) or a-z (lowercase) or _(underscore).
 C++ treats uppercase and lowercase characters differently.
For example, DATA is not same as data.
 No special character is allowed except _ (underscore).
 A keyword cannot be used for naming an identifier.
 Identifiers should be of reasonable length (but ANSI C has not enforced any restriction on
this aspect).

C++ treats uppercase and lowercase differently. But we can use the keywords in uppercase as identifiers,
since the complier considers while, if etc. as keywords. But it does not consider the same words in
uppercase i.e., WHILE, IF etc. as identifiers. However it is not treated as a good programming practice
to make use of keywords as identifiers.

149
Introduction to C++

7.3.2 Keywords
Keyword is a predefined word that gives special meaning to the compiler. They are reserved words
which can be used for their intended purpose and should not be used as normal identifier. There are
keywords in C++ (developed by Stroustrup) as mentioned in Table7.1.
alignas (since C++11) enum return
alignof (since C++11) explicit short
and export signed
and_eq extern sizeof
asm false static
auto(1) float static_assert(since C++11)
bitand for static_cast
bitor friend struct
bool goto switch
break if template
case inline this
catch int thread_local(since C++11)
char long throw
char16_t(since C++11) mutable true
char32_t(since C++11) namespace try
class new typedef
compl noexcept(since C++11) typeid
const not typename
constexpr(since C++11) not_eq union
const_cast nullptr (since C++11) unsigned
continue operator using(1)
decltype(since C++11) or virtual
default(1) or_eq void
delete(1) private volatile
do protected wchar_t
double public while
dynamic_cast register xor
else reinterpret_cast xor_eq

Table7.1 Keywords NOTE: In Table 7.1 (since C++11)means revised in the year 2011.

Keyword is a predefined word and has special meaning to the compiler. The programmer is not allowed
to change its meaning,

150
Introduction to C++

Invariant program elements are called “literals” or “constants.” The terms “literal” and “constant” are
used interchangeably.Figure7.2
eÁw
shows the clear classification of literals. They are program elements whose
value does not change during program execution. A literal may be any of the following:
 Integer constant
 Floating constant
 Character constant
 String literal

Figure 7.2 Constants and its types

Constant is a fixed value that does not change during the execution of the program.

7.3.3.1 Integer constants


Integer constants are constants that have no fractional parts or exponents. They always begin with a
digit. We can specify integer constants in decimal, octal, or hexadecimal form. They can specify signed or
unsigned types and long or short types. When we want to specify integer constants using octal or hexadecimal
notation, we use a prefix that denotes the base and when we want to specify an integer constant of a given
integral type, we use a suffix that denotes the type.
Decimal constants: We specify a decimal constant with a nonzero digit.

Example 7.1:
int a = 1587; // Decimal constant
int b = -148; // A negative decimal constant
int c = 065; // Leading zero specifies octal constant, not decimal
151
Introduction to C++

Octal constant:
When we specify an octal constant, we should always begin with 0 followed by a sequence of digits
in the range 0 through 7. The digits 8 and 9 are errors in specifying an octal constant.

Example 7.2:
int a = 0374; // Octal constant
int j = 095; // Error: 9 is not an octal digit

Hexadecimal constants:
When we specify a hexadecimal constant, we should always begin the specification with 0x or 0X
(the case of the “x” does not matter), followed by a sequence of digits in the range 0 through 9 and a (or
A) through f (or F). Hexadecimal digits a (orA) through f(or F) represents values in the range 10 through
15.

Example 7.3:
int a = 0x5fff; // Hexadecimal constant
int b = -0X3FFF;

Unsigned constants:
To specify an unsigned type, use either the u or U suffix. To specify a long type, use either the l or L
suffix.

Example 7.4:
unsigned val= 328u; // Unsigned value
long val= 0x7FFFFFL; // Long value specified as hex constant
unsigned long val = 0776745ul; // Unsigned long value as octal constant

7.3.3.2 Floating point constants


Floating-point constants are also called as ‘real constants’. These values contain decimal
points (.) and can contain exponents. They are used to represent values that will have a fractional
part and can be represented in two forms (i.e., fractional form and exponent form).
Floating-point constants have a “mantissa,” which specifies the value of the number, an
“exponent” which specifies the magnitude of the number, and an optional suffix that specifies the
constant’s type. The mantissa is specified as a sequence of digits followed by a period, followed by an
optional sequence of digits representing the fractional part of the number.

152
Introduction to C++

Example 7.5
eÁw
18 . 45

Integer part Decimal point Fractional part

The exponent, if present, specifies the magnitude of the number as a power of 10, as shown in the
following example 7.6.

Example 7.6
23.46e0 // means it is equal to 23.46 x 100 = 23.46 x 1 = 23.46
23.46e1 // means it is equal to23.46 x 101= 23.46 x10 = 234.6
23.46e-1 // means it is equal to23.46 x 10-1= 23.46 x1/10 =2.346
- 0.2346e-1 // means it is equal to -0.2346 x 10-1= -0.2346x 1/10= -0.02346

The exponent may be specified using e or E, which have the same meaning, followed by an
optional sign (+ or -) and a sequence of digits. If an exponent is present, the trailing decimal point is
unnecessary in whole numbers such as 23E0.
Floating-point constants default to type double. By using the suffixes f or l (or F or L — the
suffix is not case sensitive), the constant can be specified as float or long double, respectively.

7.3.3.3 Character constants


Character constants are specified as single character enclosed in pair of single quotation
marks. For example:
char ch = ‘p’; // Specify normal character constant.

A single character constant such as ‘D’ or ‘r’ will have char data type. These character
constants will be assigned numerical values. The numerical values are the ASCII values which are
numbered sequentially for both uppercase and lowercase characters. For example, ASCII value of A is
65, B is 66,….,Z is 90 (uppercase characters), a is 97, b is 99,….z is 122 (lowercase characters), 0 is
48, 1 is 49,…9 is 57 (for digits). Indeed all the characters on the keyboard are assigned with an ASCII
value.
There is another class of characters which cannot be displayed on the screen (non-graphic characters)
but they have special meaning and are used for special purpose. For example, tab key, carriage return,
backspace and such character constants are called as escape sequences. The following table7.2 shows
the list of escape sequences in C++.

153
Introduction to C++

Escape Description
sequence
\’ single quote
\” double quote
\? question mark
\\ backslash
\0 null character
\a audible bell
\b backspace
\f form feed - new page
\n line feed - new line
\r carriage return
\t horizontal tab
\v vertical tab
\nnn arbitrary octal value
\xnn arbitrary hexadecimal value
Table 7.2 Escape sequences in C++

Escape sequence is a special string used to control output on the monitor and they are represented by
a single character and hence occupy one byte space.

7.3.3.4 String constants


A string literal consists of zero or more characters enclosed by double quotation marks (“). Multiple
character constants are called String constants and they are treated as an array of char. By default the
compiler adds a special character called the ‘null character’ (‘\0’) at the end of the string to mark the end
of the string. For example, the string literal has to be represented as
char str[15] =” C++ Programming”;
This is actually represented as char str[15] =” C++ Programming\0" in the memory.

7.3.4 Punctuators
Punctuators in C++ have syntactic and semantic meaning to the compiler but do not by themselves
specify an operation that yields a value. Some punctuators can be either alone or in combination, and they
can be significant to the preprocessor. The following characters are considered as punctuators:
! % ^ &* ( ) – + = { } | ~
[ ] \ ; ‘ : “<> ? , . / #

154
Introduction to C++

The functions of some of the punctuators is given in the below table 7.3.
eÁw
symbols Illustration
! used along with ‘=’ to indicate ‘not equal to’
% used along with format specifier
& used to represent address location or bitwise and operation
; used to represent statement terminator
[] used to represent array subscript
{} used to represent the starting and ending of a block of code
() used to represent function calls, group expressions, etc.
# used to represent preprocessor directive
\ used to represent escape sequence

Table 7.3 Punctuators

7.3.5 C++ Operators


An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and there are almost 45 different operators. These opera-
tors can be either ‘unary’ or ‘binary’ or even ‘ternary’ operators. The following are the different types
of operators as shown in the figure 7.3.

An operator is a symbol that represents an operation to the compiler.

Operator Name

! Logical NOT. Use to reverses the logical state of its operand. If a


condition is true then Logical NOT operator will make false.
& Address-of. Used to give the address of the operand.
~ One’s complement. Converts 1 to 0 and 0 to 1.
* Pointer dereference. Used along with the operand to represent the
pointer data type.

Figure 7.3 C++ operators

Let us examine all these mentioned operators one by one.

155
Introduction to C++

7.3.5.1 Unary operators


Unary operations have only one operand they are evaluated before any other operations containing
them gets evaluated. The following are the list of unary operators.

Operator Name

! Logical NOT. Use to reverses the logical state of its operand. If a


condition is true then Logical NOT operator will make false.
& Address-of. Used to give the address of the operand.
~ One’s complement. Converts 1 to 0 and 0 to 1.
* Pointer dereference. Used along with the operand to represent the
pointer data type.
+ Unary plus. Used to represent a signed positive operand.
++ Increment. Used to increment an operand by 1.
– Unary negation. Used to represent a signed negative operand.
–– Decrement. Used to decrement an operand by 1.

Table 7.4 Unary operators

In C++, it becomes absolutely necessary to understand about the increment and decrement operators
under unary operators and they operate on a single variable.++ is used to increment the value of the
variable by 1 and the operator can appear before or after the variable and — is used to represent
decrement the value of the operator by 1. Just like the increment operator the decrement operator can
also appear before or after the variable as shown below. Therefore,
a++ or ++a means a=a+1
b— or —b means b=b-1
If the ++/— operator is to the left of the variable then, it is called pre- increment/decrement operator
and if the ++/— operator is to the right of the variable then, it is called post increment/decrement operator.
However, in both the cases of incrementing and decrementing there will be significant change in their
values during the course of the program execution.
Consider the following statements in a program:
int a = 5,b;
…..
b = ++a;
b = a++;
In the first statement, the value of b will be 6 and in the second statement the value of b will be
still 6 and not 7 because in case of post incrementing the value is considered first and then incremented.
b = a++;

156
Introduction to C++

then, the value of b will be still 6 and not 7 because the operator is to the right of the variable
considers
eÁw
the value and then increments it.

Unary operators operate on single operand.

Example7.7 Let b=10, c=20. Evaluate the expression a = ++b + c++;


Solution:
Step1: identify the operands and its associated signs.
Here operand b is pre incremented. Therefore we need to first increment and consider the value.
Hence the value of b = 11.
The operand c is post incremented and therefore first considers the value and then increments.
Hence the value of c=20.

Step 2: Now add both b and c.


We get, a=11+20
=31.
Therefore, a=31 is the answer.

7.3.5.2 Binary operators


The binary operators are those operators that operate on two operands. They are as arithmetic
operators, relational, logical operators, bitwise, assignment operators.

7.3.5.2.1 Arithmetic Operators


The operators supported by C++ are: + - * / %
Let us assume that variable a=10 and variable b=20 then:

Operator Description Example

+ Adds two operands a + b will give 30


- Subtracts second operand from the first a - b will give -10
* Multiply both operands a * b will give 200
/ Divide numerator by denominator b / a will give 2
% Modulus Operator and remainder of after an
integer division b % a will give 0

Table 7.5 Arithmetic Operators

157
Introduction to C++

7.3.5.2.2 Relational Operators


The relational operators supported by C++ are: == !=><>= <=
Let us assume that variable a=5 and variable b=10 then:

Operator Description Example


== Checks if the value of two operands is equal or (a == b) is false.
not.
!= Checks if the value of two operands is equal or (a != b) is true.
not.

> Checks if the value of left operand is greater than (a > b) is false.
the value of right operand.

< Checks if the value of left operand is less than the (a < b) is true.
value of right operand.

>= Checks if the value of left operand is greater than (a >= b) is false.
or equal to the value of right operand.

<= Checks if the value of left operand is less than or a <= b) is true.
equal to the value of right operand.

Table 7.6 Relational Operators

158
Introduction to C++

7.3.5.2.3 Logical Operators


The logical operators supported by C++ are: &&, || and !
eÁw
Let us assume that variable a=0and variable b=1 then:

Operator Description Example


&& Called as Logical AND operator. If both the operands (a && b) is false.
are non-zero then condition becomes true.

|| Called as Logical OR Operator. If any of the two (a || b) is true.


operands is non-zero then condition becomes true.

! Called as Logical NOT Operator. Use to reverses !(a && b) is true.


the logical state of its operand. If a condition is !(a) is true. !(b) is false.
true then Logical NOT operator will make false.

Table7.7 Logical Operators

7.3.5.2.4 Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation. The truth tables for bitwise
and(&),bitwise or(|), and bitwise xor (^) are as follows:

a b a&b (Bitwise and) a | b ( Bitwise or) a ^ b ( Bitwise xor)


0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Table 7.8 Truth Table

Example 7.8:
Assume that if a = 60; and b = 13; the following operations takes place:
Step 1: converts a and b both to its binary equivalent.
a = 0011 1100
b = 0000 1101
Step 2: then performs the bitwise and, or and not operations. The result is given below.
a&b = 0000 1100 (bitwise and) = 12
a|b = 0011 1101 (bitwise or) = 61
a^b = 0011 0001 (bitwise xor) = 49
~a = 1100 0011 (bitwise not) = -60
159
Introduction to C++

The Bitwise operators supported by C++ are listed in the following table 7.9.

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists (A & B) will give 12 which
in both operands. is 0000 1100
| Binary OR Operator copies a bit if it exists in either oper- (A | B) will give 61 which is
and. 0011 1101

^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is
operand but not both. 0011 0001

~ Binary Ones Complement Operator is unary and has the (~A ) will give -60 which is
effect of ‘flipping’ bits. 1100 0011

<< Binary Left Shift Operator. The left operands value is A << 2 will give 240 which
moved left by the number of bits specified by the right is 1111 0000
operand.

>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15 which is
moved right by the number of bits specified by the right 0000 1111
operand.
Table7.9 Bitwise Operators

7.3.5.2. C++ Shorthands


C++ offers special shorthands that simplify the coding of a certain type of assignment statements.

Example 7.9 a=a+10; Can be written as a+=10;


The operator pair += tells the compiler to assign to the value of a+10. This shorthands works for all
the binary operates in C++(those that require two operands).
The general form of C++ shorthand is
Variable operator= expression
Following are some examples of C++ shorthands:
x-=10 equivalent to x =x-10;
x*=5 equivalent to x =x*5;
x/=2 equivalent to x = x/2;
x%=z equivalent to x =x%z

All assignment operators have lower precedence than the conditional operator (?).

160
Introduction to C++

7.3.5.2.5 Assignment Operators


The
eÁwassignment operators supported by C++ are listed in the table 7.10:

Operator Description Example


= Simple assignment operator, Assigns values from right c = a + b will assign value of
side operands to left side operand a + b into c
+= Add AND assignment operator, It adds right c += a is equivalent to
operand to the left operand and assign the result to left c=c+a
operand
-= Subtract AND assignment operator, It subtracts right c - = a is equivalent to
operand from the left operand and assign the result to left c=c–a
operand

*= Multiply AND assignment operator, It multiplies c *= a is equivalent to


right operand with the left operand and assign the result to c=c*a
left operand
/= Divide AND assignment operator, It divides left c /= a is equivalent to
operand with the right operand and assign the result to left c=c/a
operand

%= Modulus AND assignment operator, It takes c %= a is equivalent to


modulus using two operands and assign the result to left c=c%a
operand

<<= Left shift AND assignment operator c <<= 2 is same as


c = c << 2

>>= Right shift AND assignment operator c >>= 2 is same as


c = c >> 2

&= Bitwise AND assignment operator c &= 2 is same as


c=c&2

^= bitwise exclusive OR and assignment operator c ^= 2 is same as


c=c^2
|= bitwise inclusive OR and assignment operator c |= 2 is same as c = c | 2

Table7.10 Assignment Operators

161
Introduction to C++

7.3.5.2.6 Special Operators


The other operators supported by C++ are listed in the table 7.11:

Operator Description
sizeof () sizeof operator returns the size of a variable. For example
sizeof(a), where a is integer, will return 2.
Comma operator causes a sequence of operations to be
, performed. The value of the entire comma expression is the value
of the last expression of the comma-separated list.
. (dot) and -> (arrow) Member operators used to reference individual members of
classes, structures, and unions.
cast Casting operators convert one data type to another. For example,
int(2.2000) would return 2.

& Address operator & returns the address of a variable.


For example &a; will give actual address of the variable a.
* Pointer operator * is pointer to a variable. For example *a; will
pointer to a variable a.

Table7.11 Other Operators

7.3.5.3 Ternary operators


The ternary operators are those operators that operate on three or more operands. Ternary operator
is also called as conditional operator. The ternary operators are as follows.

Operator Description
? Conditional operator. If condition is true, expression in the TRUE
is selected, otherwise the expression in the FALE part is selected.
Table7.12 Ternary Operator

162
Introduction to C++

The operator that operates on three operands is called the conditional operator or ternary
operator.
eÁw

7.4 Precedence of operators or Hierarchy of operators


At the first it becomes absolutely necessary to know as to what is an expression? An expression is a
combination of opcode and operands. The operators could be arithmetic, relational, and logical or any
one just discussed in the previous section.
If the expression contains multiple operators, the order in which operations are carried out is called
precedence of operators. It is also called as priority or hierarchy.
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator:

If the expression contains multiple operators, the order in which operations are carried out is
called precedence of operators. It is also called as priority or hierarchy.

Example 7.9: x = 7 + 3 * 2;

Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get
multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table and those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first. The
precedence of operators along with its associativity is given in the below table 7.13.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ — (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right

163
Introduction to C++

Logical AND && Left to right


Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>=<<= &= ^= |= Right to left
Comma , Left to right
Table7.13 Precedence of operators

What is operator precedence in C++?


“The order in which different types of operators are evaluated is called as operator precedence “. It
is also known as hierarchy of operators. All operators in C++ have their own level of precedence. In any
expression, Operators having higher precedence are evaluated first. The expression is evaluated in
following sequence.
1. Arithmetic
2. Relational
3. Logical
Table 11.14 Shows the Level of Precedence.

Priority Operator Precedence


1 ! Logical Not (highest)
2 ( ) Parenthesis
3 *, /, %
4 +, -
5 >, >=, <, <=
6 ==, !=
7 && ( and)
8 || (or)
9 ! not
Table 7.14 Levels of precedence

The expression in parenthesis is evaluated first. In case of nested parenthesis the part of
expression in the inner most parenthesis is evaluated first. Next, multiplication and division operators are
evaluated. Then, plus and minus operators are evaluated. Relational operators, Logical AND, OR,
NOT and finally the assignment operator are respectively evaluated.

164
Introduction to C++

If the expression contains the operators of equal priority then the operations are performed as first-
come-first-serve
eÁw
basis.

Example 7.10: Consider the expression 5*(4+ (10-6)/2) +5.


 First of all, the expression in inner most parentheses (10-6) is evaluated.
 Second step, result of this expression is divided by 2. It results 2.
 Third step, 2 is added to 4, the entire values in parenthesis gives result equal to 6.
 Last step, 6 is multiplied by 5 which is equal to 30 then finally, added to 5 and final
result is 35.

 Any algebraic expression has to be converted to C++ expression before evaluation.


 All the variables on to the right hand side of the expression should be assigned values before
evaluation.
 If in an expression any two operators have same precedence then, the evaluation is done from
left to right.
 If nested parenthesis is encountered then the innermost parentheses is evaluated first and the
evaluated first.
 Some equivalent C++ expressions are:
 ab – cd is written as a*b – c*d
 is written as x1 =( -b + sqrt(b*b – 4*a*c)) / (2*a) and the other
expression will be x2 =( -b - sqrt(b*b – 4*a*c)) / (2*a)

7.5 Type Conversion


Converting an expression of a given type into another type is known as type-casting or type
conversion.
Type conversions are of two types, they are
 Implicit conversion
 Explicit conversion

7.5.1 Implicit conversion


Implicit conversions do not require any operator. They are automatically performed when a
value is copied to a compatible type. The C++ compiler will implicitly convert or promote values if it can
be done safely. If not it will generate a warning or an error depending on the conversion required. For
example,
short a = 2000;
int b;
b = a;

165
Introduction to C++

Here, the value of a has been promoted from short to int and we have not had to specify any type-
casting operator. This is known as a standard conversion. Standard conversions affect fundamental data
types, and allow conversions such as the conversions between numerical types (short to int, int to float,
double to int...), to or from Boolean, and some pointer conversions. Some of these conversions may
imply a loss of precision, which the compiler can signal with a warning. For example,

const int big =110232343;


const short int small = big;

Here in the above example, the compiler will most likely generate a warning about truncation as
trying to put a large number into a small variable will lose part of the number’. The compiler will make
numbers bigger (never smaller) when evaluating expressions. If you add a float to a double, it will treat
both as doubles. Add an int to a float and both are treated as floats. Add a short int to an int and both will
be added as int, and the same is true with char. For example,

char a = '2';
int b = a + 9;

This is poor code but it compiles and runs. The implicit promotion of ‘2’ to an int with a value of 50
results in it outputting 59.this is because the compiler considers the ASCII value of ‘2’ which is 50 and
therefore it outputs 59. This can be avoided with an explicit conversion.

7.5.2 Explicit conversion


C++ is a strong-typed language. Many conversions, especially those that imply a different
interpretation of the value, require an explicit conversion.

short a = 2000;
int b;
b = (int) a; // c-like cast notation
b = int (a); // functional notation

Implicit conversion will be performed by the compiler itself, without user intervention. Explicit
conversion will be performed by the user, as his need.

166
Introduction to C++

7.6 Structure of C++ Program


ForeÁw
understanding purpose let us start with a simple C++ program that prints a sentence on the
screen.

Program 7.1 A sample program

#include<iostream.h>
void main()
{
cout<<"This is first C++ program";
}

Sample run: This is first C++ program

The above program contains certain basic elements that all C++ programs possess. In The next
section, we will be able to understand in depth about the actual structure of a C++ program.

7.7 C++ program structure


Let us analyze the structure of a C++ program after knowing about the tokens and operators of
C++. From the below figure 7.4 we will get a clear idea of a C++ program structure. This figure not
only explains the structure but also gives the explanation about each statement simultaneously along with a
simple example beside it.

167
Introduction to C++

Figure 7.4 Detailed Structure of C++ Program

Let us understand each section one by one in detail by considering the above figure 7.4.

Comments or Documentation section


This is generally a comment section as discussed earlier. This section allows us to write comments
about what each statement is doing. Indeed, the comments can be added at the end of each statement in
the program. They are not executed by the complier. But, they definitely provide the required explanation
about the program to the programmers. Single line comments begin with double slash (//) and multiline
comments are enclosed between slash and asterisk ( /* ………*/ ).

Linker Section
#include<iostream.h>
#include<conio.h>
The linker section begins with a hash (#) symbol and #include…. is a preprocessor directive and
these statements are processed first by the compiler and then the rest of the statements are
compiled. These statements tells the compiler to include the header files iostream.h and conio.h into the
program.

168
Introduction to C++

Definition Section
eÁw #define PI 3.14
In this section, we can define constants, expressions, structures, functions, classes and objects. After
the linker section gets executed, the definition section is executed by the compiler and this section is
optional. In the above example, we find that PI is a constant identifier which takes the value 3.14 and
wherever this identifier is used the compiler replaces the value with 3.14 in the program.

Global declaration section


We can declare variables here and those variables which are declared before the main function
or any other function then the life or scope of such variables remain throughout function and can be used
by other functions of the program. This section is also optional and depends on the needs of the applica-
tion that is being developed. Even in the above example we have no variables declared under this section.

main ( ) function
void main( )
This instruction marks the beginning of the main function and it contains the statements that perform
the required task. This statement is executed first by the compiler when the program starts. It is also
important to note that there will be only one main( ) function in a program.

Braces {}
{ Opening braces
…..
…..
…..
} Closing braces

The statements inside any function including the main ( ) function is enclosed with the opening and
closing braces. Therefore we find the { } in the above figure 7.4 also.

Variable declaration section


In the above example program, we have declared variables and also its data types. This helps the
compiler to allocate the memory space inside the computer memory. Those variables declared inside the
function block, the life or scope of such variables remains till the end of that block only.

Executable statements section


Generally, in C++ the statements are written inside the main( ) function or any other function. These
statements can be expressions, input-output functions, conditional statements, looping statements, function
call and so on. In the above fig 7.4, we have seen the example to compute the area and circumference of
the circle.
The cout function statement is a user prompt which tells the user to input the value for the

169
Introduction to C++

radius and the text present inside the double quotes “ input the value of radius: ” is displayed on the output
screen.
The next is thecin function statement which takes the input that is given by the user. The
next two statements are C++ expressions that calculate the area and circumference of the circle
respectively.
Finally, the next two output statements display the computed area and circumference
respectively.

7.7 Importance of iostream.h


As discussed earlier, we have included some other files to our source programs using
the ‘#include<______ .h>’directive in the linker section of the program. The preprocessor is an
instruction to the compiler itself so that it deals with these directives before starting with the real
compilation process for example the first statement in the figure 7.4.

#include directive
The #include directive instructs the compiler to read and include another file in the current file.
The compiler compiles the entire code. A header file may be included in one of two ways.
#include<iostream.h>
or
#include "iostream.h"
The header file in angle brackets means that file reside in standard include directory. The header files
in double quotes means that file reside in current directory.

7.8 LIBRARY FUNCTION


C++ provides many built-in functions that save the programming time. They include
mathematical functions, character functions, string functions, console input–output functions and
some general standard library functions. Some of them are given below and also discussed in detail in
Functions chapter.

7.8.1 Mathematical Functions

170
Introduction to C++

Some of the important mathematical functions in header file math.h are


eÁw
Function Meaning
sin(x) Sine of an angle x (measured in radians)

cos(x) Cosine of an angle x (measured in radians)

tan(x) Tangent of an angle x (measured in radians)

asin(x) Sin-1 (x) where x (measured in radians)

acos(x) Cos-1 (x) where x (measured in radians)

exp(x) Exponential function of x (ex)

log(x) logarithm of x

log 10(x) Logarithm of number x to the base 10

sqrt(x) Square root of x

pow(x, y) x raised to the power y

abs(x) Absolute value of integer number x

fabs(x) Absolute value of real number x

 All of the trigonometric functions take double arguments and have double
return types.
 The trigonometric functions work in radiansrather than degrees.
 Radians =

171
Introduction to C++

7.8.2 Character Functions


All the character functions require ctype.h header file. The following table lists the
function.

Function Meaning

isalpha(c) It returns True if C is an uppercase letter and False if c is lowercase.

isdigit(c) It returns True if c is a digit (0 through 9) otherwise False.

isalnum(c) It returns True if c is a digit from 0 through 9 or an alphabetic character (either upper
case or lowercase) otherwise False.

islower(c) It returns True if C is a lowercase letter otherwise False.

isupper(c) It returns True if C is an uppercase letter otherwise False.

toupper(c) It converts c to uppercase letter.

tolower(c) It converts c to lowercase letter.

7.8.3 String Functions


The string functions are present in the string.h header file. Some string functions are given
below:

strlen(s) It gives the no. of characters including spaces present in a string S.

strcat(s1, s2) It concatenates the string s2 onto the end of the string s1. The string s1 must
have enough locations to hold s2.

strcpys(s1, s2) It copies character string s2 to string s1. The s1 must have enough storage
locations to hold s2.

strcmp((s1, s2)==0)
strcmp((s1, s2)>0) It compares s1 and s2 and finds out whether s1 equal to s2, s1 greater than
strcmp((s1, s2) <0) s2 or s1 less than s2.

strcmpi((s1, s2)==0) It compares s1 and s2 ignoring case and finds out whether s1 equal to s2,
strcmpi((s1, s2)>0) s1 greater than s2 or s1 less than s2.
strcmpi((s1, s2) <0)

strrev(s) It converts a string s into its reverse

strupr(s) It converts a string s into upper case

strlwr(s) It converts a string s into lower case

172
Introduction to C++

7.8.4 Console I/O functions


The following are the list of functions is in stdio.h
eÁw

getchar() It returns a single character from a standard input device (keyboard). It takes no
parameter and the returned value is the input character.
putchar() It takes one argument, which is the character to be sent to output device. It also returns
this character as a result.
gets() It gets a string terminated by a newline character from the standard input stream stdin.
puts() It takes a string which is to be sent to output device.

7.8.5 General purpose standard library functions


The following are the list of functions is in stdlib.h

randomize() It initializes / seeds the random number generator with a random number
random(n) It generates a random number between o to n-1
atoi(s) It converts string s into a numerical representation.
itoa(n) It converts a number to a string

7.8.6 Some More Functions


getch() and getche() functions
The general form of the getch() and getche () is
ch = getche();
ch1 = getch();
ch and ch1 are the variables of type character. They take no argument and require the conio.h
header file. On execution, the cursor blinks, the user must type a character and press enter key.
The value of the character returned from getche() is assigned to ch. The getche() function echoes
the character to the screen. Another function, getch(), is similar to getche() but does not echo character to
the screen.

173
Introduction to C++

Review questions
One mark questions:
1. Who developed C++?
2. C++ is a subset of C. True or false?
3. Mention any two characteristics of C++.
4. Mention the characteristics of C++.
5. Define token.
6. Mention any two tokens of C++.
7. What is an identifier?
8. Keyword can be used to name an identifier. True/false
9. Mention any two keywords in C++.
10. What is a keyword?
11. What is a constant?
12. What is an integer constant?
13. What is an octal constant?
14. What is a hexadecimal constant?
15. Give an example for integer constant.
16. Give an example for octal constant.
17. Give an example for hexadecimal constant.
18. Give an example for float constant.
19. Give an example for character constant.
20. Give an example for string constant.
21. What are escape sequence?
22. Mention any two escape sequences.
23. What are punctuators?
24. Mention any two punctuators.
25. What is an operator?
26. What are unary operators?
27. Mention any two unary operators.
28. Give the output for the expression y=++x-x++ if x=10.
29. What are binary operators?
30. Mention any two binary operators.
31. Mention the operators supported by arithmetic operators.
32. Mention the operators supported by relational operators.
33. Mention the operators supported by logical operators.
34. Mention the operators supported by bitwise operators.
35. Give an example for assignment operators.
36. Give an example for sizeof operator.

174
Introduction to C++

37. What are ternary operators?


38. What
eÁw is an expression?
39. What is operator precedence?
40. Convert the expression l= 2 into equivalent C++ expression.
41. Convert the expression a + b + b = c2 into equivalent C++ expression.
2 2 2

42. Convert the expression into equivalent C++ expression.


43. What is type casting?
44. Mention the types of type casting.
45. Mention any two math.h functions.
46. Mention any two ctype.h functions.
47. Mention any two string.h functions.
48. Mention any two functions of stdio.h.
49. Mention any two functions of stdlib.h.
50. Differentiate between getch() and getche().

Two marks questions:


1. Mention any two characteristics of C++.
2. Mention any four tokens of C++.
3. Mention any two rules for naming an identifier.
4. Mention the types of constants of C++.
5. Explain integer constant with suitable example.
6. Explain octal constant with suitable example.
7. Explain hexadecimal constant with suitable example.
8. Explain float constant with suitable example.
9. Explain character constant with suitable example.
10. What are escape sequences? Mention any two escape sequences.
11. Explain string constant with suitable example.
12. Explain unary operators with suitable example.
13. Explain arithmetic operators with suitable example.
14. Explain logical operators with suitable example.
15. Explain bitwise operators with suitable example.
16. Explain the type conversions briefly.
17. Give an example of a simple C++ program.
18. Mention any two math.h functions.
19. Mention any four ctype.h functions.
20. Mention any four string.h functions.
21. Mention any four functions of stdio.h.
22. Mention any four functions of stdlib.h.

175
Introduction to C++

Three marks questions:


1. Mention any four characteristics of C++.
2. Explain about character set and tokens I C++.
3. Summarize the rules for naming an identifier.
4. Explain about Integer constants with suitable examples.
5. What are escape sequences? Mention any four escape sequences.
6. Explain any four unary operators.
7. What is an expression? Explain the precedence of operators with suitable example.
8. Explain implicit and explicit type conversions with suitable examples.
9. Explain the detailed structure of a C++ program.
10. Explain mathematical and character library functions.
11. Explain string and stdlib.h functions.

Five marjks questions


1. Who developed C++? Explain the characteristics in detail.
2. Explain the various tokens of C++.
3. Explain the constants in C++ with suitable examples.
4. What are escape sequences. Explain the various escape sequences.
5. What are binary operators? Explain the various binary operators with suitable examples.
6. Explain unary and ternary operators with suitable examples.
7. Explain the precedence of operators with suitable examples.
8. Explain the detailed structure of C++ program with suitable programming example.
9. Explain the various library functions of C++.

176

You might also like