C

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

3.

INTRODUCTION TO C++

INTRODUCTION Bjarne Stroustrup at Bell Labs initially developed C++ during the ears1980

was designed to support the features of C such as efficiency and low-level support fo system
level codimppadded to this were features such as classes with inheritance and virtual functions,
derived from the Simula67 language, and operator overloading, deriver from Algol68. C++ is
best described as a superset of C. with full support for objec

oriented programming. This language is in wide spread use. C++ programs are fast and
efficient, qualities, which helped make C++ an extremely popular programming language.

Getting started:

To write any C++ program (usually known as source code and file in which you save this
program is known as source file.), you need a text editor. Text editor software(supported by
underlying platform) that allows you to create and edit text files. While after coding is over, to run
your program, that should be made error free, this process is known as compilation and
compiler is a software tool which is doing this job It converts your source code into machine
understandable code(known as object code) also displays the grammatical(syntactical errors in
your program.

C++ programs can be created using any text editor. e.g. on Unix Operating System platform,
use vi or ed text editor for creating and editing the source code. While on DOS Operating
System, we can use edlin or any other editor available.

Some systems like Turbo C++ and Borland C++ provide an integrated program development
environment (IDE) under MS-DOS. They provide a built-in editor and a menu bar, which
includes options such as file, edit, compile and run. We can create and save the source files
under the file option and edit them under the edit option. (C++ programs are saved using file
extension .cpp). We can then compile the program under the compile option and execute it
under the run option. The run option can be used without compiling the source code. In this
case, the run command causes the system to compile, link and run the program in one step.

Another programming environment by Microsoft that runs under Windows is VISUAL


C++(VC++). Visual C++ is a visual programming environment in which basic program
components can be selected through menu choices, buttons, icons and other predetermined
methods. (Refer practical section for TCC and VC++ editors.)

int

Introduction to C++

Writing a Simple C++ program:


1. #include <iostream.h>

2. void main ()

3. (

4. cout << "Hello and Welcome to world of C++\n";

5.)

Output is:-- Hello and Welcome to world of C++.

Explanation of the program:

Here the first line in the program deals with the including of header file (iostream is Input Output
stream and known as preprocessor directive). It is needed to support all the in built io functions
like cout (in this example.). The identifier lostream is the name of the file in standard C++ library,
iostream included in brackets is known as standard header.

Second line is the main function within the body of which you start writing the code for your
program. Every C++ program must include one and only one main function.

3rd and 5th line (and) actually contains program body 4th statement will output the given
message on screen. Symbol << represents C++ output operator. When this statement gets
executed, the characters enclosed in quotation marks ("") are sent to standard output
device(screen).

Now let's study various programming elements required to write a C++ program.

3.1 DATA TYPES IN C++

The following chart shows different data types in C++.

Data types in C++

Derived

User defined

Class

Built-in
Floating

Pointer

float

void

double

Structure Union

35

Enumeration

Integral

char

Array Punction

Range"

Introduction to C++

Character or integer 8 bits length.

signed: -128 to 127

36

Built-in data types

Name

Bytes Description

char

short
2

Integer 16 bits length.

Song

14

Integer 32 bits length.

int

unsigned: 0 to 255

signed: -32768 to 32767

unsigned: 0 to 65535

signed:-2147483648 to 2147483647

unsigned: 0 to 4294967295

Integer. Its length traditionally See short, long depends on the length of the system's Word type,
thus in MSDOS it is 16 bits long. whereas in 32 bit systems (like Windows 9x/2000/NT and
systems that work under protected mode in x86 systems) is is 32 bits long (4 bytes).

floating point number.

double precision floating point number.

float

3.4e+/-38 (7 digits)

double

1.7e+/-308 (15 digits)

long 10
long double precision floating point number.

1.2e+/-4932 (19 digits)

double

bool

Boolean value. It can take one of true or false

two values: true or false NOTE: this is a type recently added by the ANSI-C++ standard. Not all
compilers support it.

Values of columns Bytes and Range may vary depending on your system. The values included
here are the most commonly accepted and used by almost all compilers. Both C and C++
compilers support all the built-in (also known as basic or fundamental) data types. Here vold is a
generic "nontype." void type is used as the return type for functions that do not return a value.
With the exception of void, the basic data types may have several modifiers preceding them to
serve the needs of various situations. The modifiers signed, unsigned, long and short may be
applied to character and integer asic data types. However, the modifier long may also be
applied to double. Data type representation is machine specific in C++.

Introduction to C++

Type Modifiers

unsigned:--Doesn't use sign bit (assumes int if base type is omitted). long:--May have twice as
many bytes as base type (assumes int if base type is omitted). short:-- May have half as many
bytes as base type (assumes int if base type is omitted). const:--Constant (values can't be
changed during execution).

37

Compound types -

a) pointer

b) arrays c) functions

d) references

e) classes

f) unions
g) enumerations

(we will study these in the next Part.)

3.2 VARIABLES

Declaration of a variable involved name of the variable & its data type. Variables can be
declared anywhere before they are used..

Syntax: data-type var 1, var 2, ...... e.g.: int varname:

and they are optionally initialized by the assignment of a literal value

e.g. float varname=0;

Multiple variables of the same type are declared as a comma-delimited list after the type, e.g.
char varl, var2;

A valid variable name may consists of alphabet, digits, underscore, but it can't start

with a digit. is not a valid variable name since it starts with digit.

e.g. int 45abc; float f=3.14 23; is not a valid variable name since it contains space.

( Refer topic identifiers) C++ uppercase and lowercase variables are treated as different
variables.

In Variables have scope, that defines where from they can be refereed. Accordingly they can
have global and local scope. If declared outside functions, variables have global scope (

i.e. can be referenced from anywhere in the program) While if declared inside a function,
variables have local scopei.e, can be referenced only from within that function. (for details refer
topic scope and visibility.)

3.3 CONSTANTS

Constants: are declared with the "const" keyword, a type, their name, and an assignment of
their constant value. This value must match the declared type, and is fixed for the duration of
the program.

38

Syntax: const data type const name = value; e.g const char Blank: const float Pi3.14;
Types of Constants

1) Numerical constants

Introduction to C++

a) Integer constant-declared with const keyword and has fixed integer value. e.g. const int i= 10;

b) character constant: declared with const keyword and has fixed character value.

e.g. const char a= ""; When C++ compiler encounters such a character constant, it translates it
into the corresponding ASCII code and stores that number (ASCII character set is a way of
representing characters).

Character escape sequences: Back slash (1) alters the meaning of the character that follows it.

e.g. the character 'a' when typed after backslash, i.e. la will mean to produce an available or
visual alert signal.

la (alert)

lb (backslash)

Introduction to C++

39

Floating point constants default to type double. Otherwise, the following suffixes can be used: f
for float or L for long double

d) String constant: A sequence of two or more characters surrounded by double quotes is called
a string constant. This can also be defined as an array of character constants. e.g. char
arr[5]="abcde";

(refer topic arrays in the next part.)

e) Hexadecimal and octal constants: In day to day use, we use decimal constants having base
10 Numbers can also be specified using base 8 & 16. Numbers represented using base 8 are
having octal number system (uses 0-7 digits) while having base 16, are having Hexadecimal
number system (uses numbers from 0 to 9 and letters A to F) The integer constants can be
specified in hexadecimal or octal form. The octal number begins with letter O and hexadecimal
number begins with Ox.
e.g. OxAB is a hexadecimal no. 0156 is a octal number

2) Defined constants

#define Directive(PREPROCESSOR directive:)

The #define directive, causes a macro or symbolic name to be defined as a macro.ie.it sets up
an equivalence between identifier and a text phrase.

Syntax: # Or

define macro_name replacement_list

appearing at the beginning of the program specifies #define PI 3.14159 that the identifier PI will
be replaced by text 3.14159 throughout the program. No semicolon should be specified. It can
appear anywhere in the program, but normally specified at the beginning of your main program.

Backslash character

Meaning

Produces an available or visible alert

signal.

#define identifier text phrase

Moves the cursor bar one space

f (form feed)

Moves..... to the next page

In (new line)

Prints a new line

Ar (carriage return)

Prints a carriage return

t (horizontal tab)

Prints a horizontal tab


w (vertical tab)

Prints a vertical tab.

c) Floating point constant: Also called as real constants.

e.g. const double pi = 3.14;

it can also be written using exponential notation.

e.g. number 1234.56 is written as 1.23456E3. It indicates how many places the decimal point
must be moved to change the number to the ordinary decimal notation.

Suffixes for Numerical Constants

Integer constants default to the smallest integer type that can hold their value. Otherwise, the
following suffixes can be used (alone or together): u for Unsigned or L for Long

e.g

# #define arrSize 100 so the line char arr[arrSize] expands as char arr[100];

define NEWLINE n

3 ) Symbolic constants: Enumerations

In addition to the predefined data types C++ allows you to define your own special data types.
This is done using several ways; one of the ways is to use Enumeration. An enumeration of
symbolic constants is introduced by an enum declaration. This is useful for declaring a set of
closely related constants.

Syntax: enum typename (enumeration-list );

Here enum is a keyword, typename defines identifier that names the type being defined, and
enumeration list stands for a list of names of the integer constants.

Introduction to C++

40

enum (north, south, east, west); introduces four enumerators which have integn values starting
from 0 (Le., north is 0, south is 1, etc.) The default numbering of enumerators can be overruled
by explicit initialization: like, enum (north = 10, south, east = 0, west); Here, south is 11 and west
is 1. An enumeration can also be named, where the name becomes a user-defined type. This is
useful for defining variables that can only be assigned a limited set of values.

enum Days (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);

Days d;

So here d can only be assigned one of the enumerators for Days.

Use: Enumerations are particularly useful for naming the cases of a switch statement. (Refer
switch-case control structure)

e.g. switch(d)

case Sunday:

case Monday:

1/...

case Tuesday:

case Wednesday:

1/... etc...

3.4 COMPILER TOKENS

When a C++ compiler analyses a program, it breaks the program into tokens. A token is a
distinct unit that is recognizable by the compiler. There are five categories of tokens:

⚫ keywords
literals

identifiers operators and

white space includes: blanks, horizontal and vertical tabs, new line and form feed

characters and comments

Notes:
In order to separate keywords, literals and identifiers, some white space is required within a
program. White space may also be used to provide documentation in the form of comments
(comments are explained later in this chapter) and to make the program readable (e.g. by
indenting statements). A C++ compiler takes each token to be the longest sequence of
characters that can be used to form that token. Of course, it does this by starting at the
beginning of the program and proceeding in a forward direction through the source code.

Now let's study each of the tokens one by one.

Introduction to C++

KEYWORDS

Following are the keywords of the C++ language, (total 48). Keywords should be considered to
be reserved. Keywords are not allowed to be used as variable names. They

are as follows: asm, auto, break,case, catch,char, class, const, continue default, delete, do
double else enum, extern float for friend goto if, inline, int, long, new operator, private, protected,

public, register, return, short, signed, sizeof, static, struct, switch, template, throw, try, typedef,
union, unsigned, virtual, void, volatile, while

INDENTIFIERS

A valid identifier is a sequence of one or more letters, digits or underline symbols

() there is no limit to the length of an identifier, although for some compilers only

first 32characters of an identifier are significant

Neither spaces nor marked letters can be part of an identifier. Only letters, digits

and underline characters are valid

the underscore character counts as a letter, In addition, variable identifiers should always begin
with a letter. They can also begin with an underline character

(), In significant and all characters are considered significant.

no case they can begin with a digit.


case is ⚫language's keywords should not be used to define an identifier
LITERALS:

Literal may be, character constant, integer constant, floating point constant, string

constant.

3.5 OPERATORS IN C++

An operator does some operation on operands and this operation is normally specified by
operator's symbol. C++ has many operators, mainly classified as unary operators, working on
single operand and binary, working on 2 operands.

Although C++ allows us to multiple meanings to the operators, yet their association and
precedence remains same. E.g. (*) multiplication operator is having higher precedence than (+)
add operator.

Following table lists all the C++ operators in order of non-increasing precedence. An expression
involving operators of equal precedence is evaluated according to the associability of the
operators.

41

1Introduction to C++

Associativity

Introduction to C++

7:

Operator(s)

Description(s)

right to left

Global scope (unary)

left to right

0
Function call

left to right

Value construction

left to right

Array element reference

Pointer to class member reference

left to right

left to right

Class member reference

Unary minus and plus

zight to left

Increment and decrement

right to left

Logical negation and I's complement

right to left

Pointer dereference (indirection) and

right to left

address

Sizeof

Size of an object
right to left

(ope)

Type cast (coercion)

right to left

Pointer to member selector

left to right

Pointer to member selector

left to right

4%

Multiplication, division and modulus (remainder)

left to right

Addition and subtraction

left to right

Shift left and shift right

left to right

cg. Following arithmetic separators need 2 operands. +(Addition or plus) -(Subtraction or minus)
(Multiplication or star) /(Slash or division) % (Modulus separators for remainder) This operator
can't be applied with floats or double type. a+b,c/d, ab, etc.

Less than, less than or equal, greater than, greater than or equal

left to right

Equality and inequality

left to right

&
Bit wise AND

left to right

Bit wise XOR

left to right

Bit wise OR

left to right

&&

Logical AND

left to right

Logical OR

left to right

43

Conditional expression

right to left

Assignment

right to left

Comma

left to right

Brackets are evaluated from the inside out, when dealing with multiple operators of the same
level. Level evaluate from left to right

Some of the Important operators


Arithmetic operators: They are used for mathematical calculations. An arithmetic expression is
made up of constants, variables, a combination of both or a function call, connected by
arithmetic operators. Following are the subtypes:

a. Unary arithmetic operator

Needs only one operand.

e.g. +a, -buses unary operator namely (positive) and (negative).

b. Binary arithmetic operator

Needs 2 operands.

Here it gives remainder after division. eg. 5%2 will give I as a remainder while 5/2 will give 2 as
a quotient.

c. Ternary arithmetic operator

Needs 3 operands. This is one of the special features of C++ language. (See conditional
operator later in this chapter).

2) Increment and decrement operators

In some situations, a need may arise to increase or decrease, value of a variable by 1. C++
provides special operators ++ and--to do the same.

Mind it, these operators are unary Le. warning on a single operand.

a++, b- value for processing. e.g. ++a,-b b. Postfix: First take the value of the variable increment
or decrement the variable. Eg

Use of Prefix and Postfix Suppose initial values of a and b are 5 and 5 respectively.

Suppose, I do postfix operation on it ie. a++ and band print them. Here values of a and b remain
unaltered. i.c. 5 and 5 only. While after postfix operation is done, values of a and b are printed
them will be changed to 6 and 4 respectively.

44

Introduction to C++
Also it is illegal to increment or decrement constant of floating-point data type. The incrementing
and decrementing can be of 2 types: a. Prefix: first increment/decrement the value of the
variable and then take this new

Introduction to C++

45

After testing the conditions, they return logical status (true or false) They may be unary or binary
operators, and the operands may be constants, variables or even expressions. The operands
may be integers/floating point numbers.

Result

Returns lif a and b are nonzero else returns. O

Returns 1 if a or bis nonzero, else 0

Returns 1 if a is zero else returns O

Operator Logical AND

Symbol

Form

a&&b

Logical OR

allb

Logical negation

la

if ( (a < b) && (a<c))

3) Relational operator:

These are used to test the relation between 2 values. All C++ operators are binary

cout << "a is smallest";


operators and hence require 2 operands. operator. It returns zero when the relation is false
while nonzero when it is true, A relational expression is made up of 2 arithmetic expressions
connected by a relational

1 Hierarchy of logical operators --

Logical NOT (1) operator has a higher precedence than other,

Operator

Symbol

Form

Result

Less than

<

a<b

Returns 1 if a is less than b otherwise 0

While AND (&&) has higher precedence than logical OR (II) They have lower precedence than
the relational and arithmetic operators. Truth (Boolean) table for! operator-takes only I
operand(used for negation)

Greater than

<

Returns 1 if a is greater than b otherwise 0

Less than

a <= b

Or equal to

Greater than

Returns I if a is less than or equal to botherwise 0


Operator

Operand

(false) 0

(true) 1 or nonzero

Result

>=

a >= b

Returns 1 if a is greater than or equal to botherwise 0

Truth (Boolean) table for && operator: Takes 2 operands.

Or equal to

Equal to equal to

a ==b

Returns 1 if both are equal (same)

Operand 1

(&&) Operator

Operand 2

Result

False (0)

&&

False (0)
0

Not equal to

1=

a! = b

Returns I if both values are not equal

True

&&

False (0)

(nonzero)

These operators are having lower precedence than arithmetic operators. a+b*c>d%f is
evaluated as

c.g

(a + (b + c)) > (d% * f) operators: (Boolean operators)

4) Logical

They combine the results of one or more expression and the resultant expression is called as
logical expression.

If both the operands are true (nonzero) or if they are the expression returning true value then
only result is true otherwise false. )

False (0)

&&

Trie

(nonzero)

True (nonzero
True

&&

1 (nonzero)

(nonzero)

a>b

48

Introduction to

Introduction to C++

Shifting operand one bit to the right is equivalent to dividing that number by 2.

eg 32>> 1 gives 16

32>> 2 gives 8

c) Left shift (<<) operator

It shifts each bit in the operand to the left and zeros are added to right of the number.

e.g. binary representation of a number is 11001001 So when it is left shifted by 1, it's equivalent
is 10010010

Left shifting by 1 is equivalent to multiplying number by 2.

d) Bitwise AND operator (&)

It works on 2 operands and both the operands should be the same data type as well as

either char or int. The purpose of AND operator (&) is to clear the given bit.

1 bit

2 bit

0
0

&

1 bit & 2 bit

Result

c) Bitwise OR operator (1)

It also works on 2 operands. It is used to set the resultant bit to 1.

I bit

2nd bit

1 bit

2 bit

0
1

e.g.

Result

1) Bitwise XOR (^) operator

It works on 2 operands. It sets the resultant bit if both the bits on which it operators are not
equal

Bit 1

Bit 2

Bit

1 Bit 2

1
1

9) Operators dealing with streams

a) Insertion operator (<<)

49

Stream decides flow of data. There are many types of streams in C++,but dealing with input and
output is called iostream. The operator dealing with output stream is called insertion or put to
operator. It inserts the contents of the variable on its right to the object on its left. This operator
is used along with output stream.

cout << a;

Here value at variable a declared in the program is printed on standard output

device.(screen) While, cout << "a"; will display character a (included in double quotes)

on the screen.

b) Extraction operator (>>)

It is get from operator. It extracts/takes the value from the standard input device Le. keyboard
and assigns is to the variable on its right. It is associated with the input stream e.g. cin >> a;

So value entered by the user from keyboard is assigned to variable a declared in the program.

10) Comma Operator

Multiple expressions can be combined into one expression using the comma operator. The
comma operator takes two operands. It first evaluates the left operand and then the right
operand, and returns the value of the latter as the final outcome.
c.g int m, n, min; int mCount = 0, Count = 0;

50

min = (m <n? m: nCount++); Here when Count++, m; Pis evaluated and the value of m is stored
in mis

Otherwise, nCount++ is evaluated and the value of n is stored in min. This operator can also be
used in multiple assignments in for loop

c.g for(int i=0,int j=1; ic=10; i++j)

11) The sizeof Operator

C++ provides a useful operator, sizeof, for calculating the size of any data item or type takes a
single operand, which may be a type name (e.g., int) or an expression (e.g., 100 and returns the
size of the specified entity in bytes. The outcome is totally machine dependent. Following
program illustrates the use of sizeof on the built-in types we huve encountered so far,

#include <iostream.h>

void main (

cout << "char size = " << sizeof(char) <<" bytes\n"; cout << "char* size = " << sizeof(char*) <<<"
bytes\n"; cout <<"short size="<<sizeof(short) << "bytes\n"; cout << "int size = " << sizeof(int) <<"
bytes\n"; cout << "long size = " << sizeof(long) <<"bytes\n"; cout << "float size="<< sizeof(float)
<<"bytes\n"; cout << "double size = " << sizeof(double) << " bytes\n"; cout << "1.55 size=" <<
sizeof(1.35) << "bytes\n"; cout << "1.551. size="<< sizeof(1.45L) << "bytes\n"; cout << "string
size = " << sizeof("welcome") <<"bytes\n";

When run, the program will produce the following output

char size 1 bytes char size 2 bytes bort size = 2 bytes int size = 2 bytes long size = 4 bytes float
size=4 bytes double size 8 bytes 1.35size8 bytes 145L size 10 bytes string size = 7 bytes

Introduction to C++

12) Scope Resolution Operator

C++ is also a block-structured language. Blocks and scopes can be used in constructing
programs. We know that the same variable name can be used to have different meanings in
different blocks. The scope of the variable extends from the point of its declaration till the end of
the block containing the declaration. A variable declared inside a block is said to be local to that
block. Consider the following segment of a program:

int x = 10; int x = 1:

The two declarations of x refer to two different memory locations containing different values.
Statements in the second block can not refer to variable x declared in the first block and vice
versa. Blocks in C++ are often nested. For example, the following style is common:

int x = 10;

int x= 1;

Block 2

Block 1

1 Block 2 is contained in block 1. Note that a declaration in an inner block hides a declaration of
the same variable in an outer block and therefore, each declaration of x causes it to refer to a
different data object. Within the inner block, the variable x will refer to the data object declared
therein.

52

Introduction to C++

resoluties In C, global version of a variable cannot be accessed from within the inner a new
operator: called the scope resolves this problem by introducing operator. This can be used to
uncover a hidden variable. It takes the following form:

Syntax: variable_name;

This operator allows access to the global version of a variable. Following progra illustrates
difference between local and global variable

#include <iostream.h>

int m = 10i

void ()

Int m = 20
// global m

// m redeclared, local to main

int k = m_{i}

int n = 30

// m declared again

// local to inner block

Introduction to C++

53

The new operator can be used to create objects of any type. It takes the following general

form: Syntax: pointer variable = new data type;

Here, pointer variable is a pointer of type data-type. The new operator allocates sufficient
memory to hold a data object of type data-type and returns the address of the

object. The data-type may be any valid data type. The pointer-variable holds the address

of the memory space allocated.

e.g Where p is a pointer of type int and q is a pointer of type float. Here, p and q must have
already been declared as pointers of appropriate types. Alternatively, we can combine the
declaration of pointers and their assignments as follows:

p = new int:

q = new float:

int p = 1 new int;

float new float: * q = 1

Subsequentlystatements

cout <<"we are in inner block\n";


cout <<"k=" <<k<<"\n"; cout <<"local m =" <<m<<"\n";

cout <<" global m = "<<:: m <<"\n";

output is:

we are in inner block

k=20

local m = 30

global m = 10

12) Memory Management Operators (new, delete)

We use dynamic allocation technique when it is not known in advance how much of memory
space is needed. C++ supports define two unary operators new and delete that perform the task
of allocating and freeing the memory in a better and easier way. Since these operators
manipulate memory on the free store, they are also known as free store

operators. (Also refer topic pointers)

An object can be created by using new, and destroyed by using delete, as and when required. A
data object created inside a block with new will remain in existence until using delete explicitly
destroys it

* p = 25 * q = 7.5

object.

will assign 25 to the newly created int object and 7.5 to the float

13) type cast operator.

C++ permits explicit type conversion of variables or expressions using the type cast

operator.

Syntax: type-name (expression)

e.g.

average sum/float (i);


Type conversions: Simple Type Conversion

A value in any of the built-in types we have seen so far can be converted (type-cast) to

any of the other types. For example:

(int) 3.14

(long) 3.14

(double) 2

(char) 122

(unsigned short) 3.14 // gives 3 as an unsigned short

// converts 3.14 to an int to give 3

// converts 3.14 to a long to give 3L

// converts 2 to a double to give 2.0 // converts 122 to a char whose code is 122

As illustreted by these examples, the built-in type identifiers can be used as type operators.
Type operators are unary (i.e., take one operand) and appear inside brackets to the left of their
operand. This is called explicit type conversion. When the type name is just one word, an
alternate notation may be used in which the brackets appear around the

operand: int(3.14) is same as (int) 3.14

Introduction to C++

54

Implicit Conversions (automatic conversions) We can mix data types in expressions m-5+2.75

is a valid statement. Wherever data types are mixed in an expression, C++ performa the
conversions automatically. This process is known as implicit or automatic conversions When the
compiler encounters an expression, it divides the expressions into su expressions consisting of
one operator and one or two operands. For a binary operator, i the operands type differs, the
compiler converts one of them to match with the other using the rule that the "smaller" type is
converted to the "wider" type. For example, if one of the operand is an int and the other is a flost
the int is converted into a float became a float is wider than an int. This happens when values of
different types are mixed in
expression. eg. double d=1; // d receives 1.0

i=10.5; // i receives 10

i=i+d; // means: i= int(double(i)+d)

int In the last example, i + d involves mismatching types, so i is first converted to double
(promoted) and then added to d. The result is a double, which does not match the type of on the
left side of the assignment, so it is converted to int (demoted) before being assigned to i

14) stream manipulation operators

For formatting the data display, manipulator operators are used. Normally used with (<<)
operator to modify or manipulate the way the data is displayed. These are present in

<iomanip.h>header file. Some of the useful stream manipulators are:-

dec

Sets base 10 integers.

endl

Sends a new line character.

ends

Sends a null (end of string)

character.

flush

Flushes an output stream.

hex

Sets base 16 integers.

oct

Sets base 8 integers.


setw(int)

Sets field width.

e.g

cout <<"a="<<a<<endl;

cout <<"b="<<b<<endl;

Introduction to C++

55

Here endl is a stream manipulator, causing a linefeed to be inserted into stream. Thus values of
a and b are displayed on 2 different lines.

3.6 COMMENTS in C++

Comments are important part of any program even though they are not mandatory to be given.
Normally they are used to make program readable. The compiler ignores comments, so they do
not add to the file size or execution time of executable program. They can be specified in C++
using // of the text to be cominented */ is a single line comment,

while // is used as a multiline comment. eg. #include<iostream.h void main()

int a=10;

//Following declaration will display value of a on screen

cout<<"a="<<x;

So in this program the text "Following declaration will display value of a on screen

won't be compiled, so it will not be displayed on the screen. Comments are useful to make
program readable, if programming code is large enough.

3.7 SCOPE and VISIBILITY

The scope or visibility of a variable determines whether it can be accessed from other functions
in the same source file or in other source files. The position of an identifier within a block is also
a factor in determining scope. In others words it is that part of a program over which the
identifier can be seen by other identifiers and used by other identifiers.
External variables, defined outside any block and memory for these is allocated once. Even
though the external variable is declared more than once, it only has memory allocated to it once.
Variables can be declared as global variables, available to everything. these are also known as
external variables. External variables are defined outside of any functions and retain their values
during the course of a program.

Static variables are variables that are local to a function but which (unlike auto variables) retain
their values between invocations of the function these are internal static variables. The second
kind of static are external or global variables that are local to a file but not a part of any function.
The main use of these is to hide the variable so that other source code files don't see the
variable. Static storage comes from a different memory allocation it is allocated from a static
area of memory so static variables within

56

Introduction to C++

functions can retain their values between calls to the functions. Static variables can be initialized
to some value other than 0 but will only be initialized at the first call.

Automatic variable inside a function doesn't exist until the function is called. At tha time the
memory for the automatic variable is allocated dynamically from a memory Stack and released
wire the function is finished. Auto variables are not initialized at stan up but each time they are
called and do not retain their values.

#include <iostream.h

int Integer; char acharacter;

char string [20]:

unsigned int HumberOfSons:

main ()

unsigned short Age;

Global variables can be referred anywhere in the code, within any function, whenever it is after
its declaration.

Global variables

fleat Allumber, Anotherûne;


Local variables

Instructions

cout << "Enter your age:

cin >> Age:

The scope of the local

variables is limited to the code level in which they are declared. If they are declared at the
beginning of a function (like in main) its scope is the whole main function. This meani that if in
the example above, moreover than the function main() another function existed, the local
variables declared in main could not be used in the other function and vice versa.

In C++, the scope of a local variable is given by the block in which it is declared (a block is a
group of instructions grouped together within curly brackets () signs). If it is declared within a
function it will be a variable with function scope, if it is declared in loop its scope will be only the
loop, etc...

In addition to local and global scopes exists the external scope, that causes a variable to be
visible not only in the same source file but in all other files which will be linked together with

You might also like