0% found this document useful (0 votes)
5 views198 pages

2 C++ Basics

C++ is a statically typed, compiled programming language that supports multiple programming paradigms and was developed by Bjarne Stroustrup in 1979. It is widely used for system programming, application development, and in sensitive sectors like banking and military due to its efficiency and object-oriented features. The document outlines the basics of C++ programming, including its structure, data types, operators, and preprocessor directives.

Uploaded by

Achyuta Gajurel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views198 pages

2 C++ Basics

C++ is a statically typed, compiled programming language that supports multiple programming paradigms and was developed by Bjarne Stroustrup in 1979. It is widely used for system programming, application development, and in sensitive sectors like banking and military due to its efficiency and object-oriented features. The document outlines the basics of C++ programming, including its structure, data types, operators, and preprocessor directives.

Uploaded by

Achyuta Gajurel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 198

Unit 2: Basics of C++ programming

1
C++
• C++ is a statically typed, compiled, general-purpose, case-
sensitive, free-form programming language that supports
procedural, object-oriented, and generic programming.

• C++ is regarded as a middle-level language, as it comprises a


combination of both high-level and low-level language features.

• C++ was developed by Bjarne Stroustrup starting in 1979 at Bell


Labs, as an enhancement to the C language and originally named
C with Classes but later it was renamed C++ in 1983.

• C++ is a superset of C.

2
Contd..
• Need of C++:
– In order to solve the complex problems and to model the real world
perfectly, C++ was developed.

– The primary goal of C++ development was to provide object-oriented


facilities for program organization together with C’s efficiency and
flexibility for system programming.

3
Contd..
• Uses of C++:
– used to write device driver programs.

– Used to write applications in sensitive sectors such as banking, military ,


etc.

– C++ is widely used for teaching and research because it is clean enough
for successful teaching of basic concepts.

– Anyone who has used either an Apple Macintosh or a PC running


Windows has indirectly used C++ because the primary user interfaces of
these systems are written in C++.

– C++ was used to develop high performance software such as Mysql,


Windows XP, Adobe products, Mozilla Firefox and many more.
4
C++ Program Structure
• // First.Cpp
// First C++ program comment
#include <iostream> preprocessor directive
using namespace std; which namespace to use
int main() beginning of function named main
{ beginning of block for main
cout << "Hello World!"; output statement
return 0; string literal
send 0 to operating system
} end of block for main

//other codes- function definitions

5
Contd..
• Program 1: Program to print a sentence on the screen.

6
Contd…
• Output:

7
Contd..
• Program2: A Program to add two number and output the sum

8
Contd….
• Output:

9
Character set and Tokens
• Character set :
– Character set is a set of valid characters that a language can recognize. A
character represents any letter, digits, or any other sign.

– C++ has the following character set :

10
Contd..
• Tokens:
– The smallest individual unit in a program is known as tokens.
C++ has the following tokens:
• Keywords

• Identifiers

• Constants

• Operators

• Special symbols.

11
Contd..
1. Keywords:
– keywords are the reserved words for special purpose and must not be
used as normal identifier names.

– Following table lists the Complete C++ Keywords :

12
Contd..
2. Identifiers:
• Identifiers refers to the names of variable, functions, arrays, classes, etc.
• The following rule is used to create a identifier:
– identifier must start with a letter or underscore symbol (_), the rest of the characters
should be letters, digits or underscores
– legal identifiers:
x x1 x_1 _abc sum RateAveragE
– illegal identifiers, why?
13 3X %change data-1 my.identifier a(3)
– C++ is case sensitive:
MyVar and myvar are different identifiers

• Note: A reserved keyword can not be used as a identifier.

13
Contd..
3. Constants:
– Constants are the data items that never change their value during a
program run.

– C++ allows the following kinds of literals :


• integer-constant

• character-constant

• floating-constant

• string-literal

14
Contd..
4. Operators: An operator is a symbol that tells the compiler to
perform specific mathematical or logical calculations on
operands(variables).
• Types of operators available in C++
– Assignment operator
– Arithmetic / Mathematical operator
– Increment Decrement operator
– Relational operator
– Logical operator
– Conditional or Ternary operator
– Binary operator
– Unary operator

15
Contd..
• Assignment operator :
– Assignment operator is used to copy value from right to left variable.
– Suppose we have, float X = 5, Y = 2;
Operator Name Description Example
X = Y, Now both X and Y
= Equal sign Copy value from right to left.
have 5
Plus Equal to operator will return
X += Y is similar to X = X
+= Plus Equal to the addition of right operand and
+ Y, now X is 7
left operand.

Minus Equal to operator will return


X -= Y is similar to X = X -
-= Minus Equal to the subtraction of right operand
Y, now X is 3
from left operand.

Multiply Equal to operator will


X *= Y is similar to X = X *
*= Multiply Equal to return the product of right operand
Y, now X is 10
and left operand.

Division Equal to operator will


X /= Y is similar to X = X /
/= Division Equal to divide right operand by left operand
Y, now X is 2.5
and return the quotient.

Modulus Equal to operator will


X %= Y is similar to X = X
%= Modulus or Mod Equal to divide right operand by left operand
% Y, now X is 1
and return the mod ( Remainder ). 16
Contd..
Arithmetic operators: Arithmetic operators are used for mathematical operations.
Suppose we have, int X = 5, Y = 2;

Operator Name Description Example

Return the addition of left and right


+ Plus (X + Y) will return 7
operands.

Return the difference b/w right operand


- Minus (X - Y) will return 3
from left operand.

Return the product of left and right


* Multiply (X * Y) will return 10
operands.

(X / Y) will return 2(both are


Return the Quetiont from left operand by
/ Division int, int doesn't support
right operand.
decimal)

Return the Modulus ( Remainder ) from left


% Modulus or Mod (X % Y) will return 1
operand by right operand.

17
Contd..
• Relational operators: Relational operators are used for checking conditions
whether the given condition is true or false. If the condition is true, it will return non-
zero value, if the condition is false, it will return 0.

• Suppose we have, int X = 5, Y = 2;


Operator Name Description Example

Check whether the left operand is greater then


> Greater then (X > Y) will return true
right operand or not.

Check whether the left operand is smaller then


< Smaller then (X < Y) will return false
right operand or not.

Check whether the left operand is greater or


>= Greater then or Equal to (X >= Y) will return true
equal to right operand or not.

Check whether the left operand is smaller or


<= Smaller then or Equal to (X <= Y) will return false
equal to right operand or not.

Check whether the both operands are equal or


== Equal to (X == Y) will return false
not.

Check whether the both operands are equal or


!= Not Equal to (X != Y) will return true
not. 18
Contd..
• Logical operators:
– Logical operators are used in situation when we have more then one
condition in a single if statement.
– Suppose we have, int X = 5, Y = 2;
Operator Name Description Example

Return true if all conditions are


if(X > Y && Y < X) will
&& AND true, return false if any of the
return true
condition is false.

Return false if all conditions


if(X > Y || X < Y) will
|| OR are false, return true if any of
return true
the condition is true.

Return true if condition if false, if(!(X>y)) will return


! NOT
return false if condition is true. false

19
Contd..
• Conditional Operator ?:
– The conditional operator is also known as ternary operator. It is called
ternary operator because it takes three arguments. First is condition,
second and third is value. The conditional operator check the condition, if
condition is true, it will return second value, if condition is false, it will
return third value.
– Syntax :
• val = condition ? val1 : val2;
– Example :
int main()
{
int X=5,Y=2,lrg;
lrg = (X>Y) ? X : Y;
cout << "\nLargest number is : " << lrg;
}
Output : Largest number is : 5

20
Contd..
• Binary operator
– Binary operators are those operators that works with at least two operands
such as (Arithmetic operators) +, -, *, /, %.

• Unary operator
– Unary operators are those operators that works with single operands such
as (Increment or Decrement operators) ++ and --.

21
Contd..
5. Special Symbols: Escape characters are known as special symbols in C++. An
escape sequence is represented by a backslash (\) followed by one or more characters.
Following table lists the C++ Escape Sequences :

22
C++ Data Types
• A data type defines a set of values that a variable can store along with a set of

operations that can be performed on that variable.

• Each and every variable and constants that we are using in our program must

be declared before its use.

• The reason behind it is that, each and every variable/constant must be placed

in some memory location. Such memory allocation is done at compile time by

the compiler.
23
C++ Data Types
• The various data types provided by C++ are:

– built-in data types,

– derived data types and

– user-defined data types

24
C++ Data Types

25
Contd..
• Fundamental data types( built-in/basic data type):

• Several of the basic types can be modified using one or more of these
type modifiers −
– signed
– unsigned
– short
– long

26
Contd..
• The following table shows the variable type, how much memory
it takes to store the value in memory, and what is maximum and
minimum value which can be stored in such type of variables.

27
Contd..

28
Contd..
• The size of variables might be different from those shown in the
above table, depending on the compiler and the computer you are
using.

• Following is the example, which will produce correct size of


various data types on your computer.

29
Contd..
• Program:

30
Contd..
• Output:

31
Contd..
• Derived data types:
– Data types that are derived from the built in data types are known as
derived data types.

– The various derived data types provided by C++ are:


• Arrays

• Functions

• Pointers and etc.

32
Contd..
• User defined data types:
– The data types that are defined by the user as per their need is called user
defined data types,

– Various user defined data types provided by C++ are


• Structures

• Unions

• Enumerations and

• classes

33
Contd..
• Example Program :

34
35
Type Conversion
• Converting an expression of a given type into another type is
known as type conversion.

• When data (constants and variables) of different types are mixed


in an expression, they are converted to the same type.

• In C++ there are two types of type conversion:


– Implicit type conversion and

– Explicit type conversion

36
Contd…
• Implicit (Automatic) Type conversion:
– An implicit type conversion is a conversion performed by the
compiler without programmer's intervention.

– There are two basic types of implicit type conversion:

• promotions and

• conversions.

37
Contd..
• Promotion
– Whenever a value from one type is converted into a
value of a larger similar data type, this is called
a promotion (or widening) For example, an int can be
widened into a long, or a float promoted into a double:

– They are always safe, and no data loss will result.

– E.g., int x =3;

float y= 2.5, z;

z=x+y;
38
Contd..
• Conversion:
– When we convert a value from a larger type to a similar smaller
type, or between different types, this is called a numeric
conversion. For example:
• double d = 3; // convert integer 3 to a double (between different types)

• short s = 2; // convert integer 2 to a short (from larger to smaller type)

– conversions may or may not result in a loss of data.

39
Contd..
• Explicit type conversion(Type casting):
– Type casting is the forceful conversion form one type to another
type.

– Sometimes a programmer needs to convert a value from one type to


another type forcefully in a situation where compiler will not do it
automatically.

– For this C++ permits explicit type conversion of variables or


expressions as follows:

• (Type-name) expression // C notation

• Type- name (expression) // C++ notation


40
Contd..
• For example:
short int a = 10000;

Short int b= long(a)* 5/2; // correct

Here if we do not cast a into long, the result of sub-expression a*5 will be
50000 which is outside of the range of data type short int and causes the
program to produce wrong result. But this case automatic type conversion
is not done by the compiler and hence programmer needs to use explicit
type conversion to produce the right result.

41
Contd..
• Program:

42
Contd..
• Output:

43
Preprocessor Directives
• preprocessor directives are lines included in the code of programs
preceded by a hash sign (#).

• These lines are not program statements but directives for the
preprocessor.
– The preprocessor examines the code before actual compilation of code begins
and resolves all these directives before any code is actually generated by
regular statements.

• These preprocessor directives extend only across a single line of code.

• can extend through more than one line is by preceding the newline
character at the end of the line by a backslash (\).

• No semicolon (;) is expected at the end of a preprocessor directive.


44
Contd..
• The #define directive:
– The #define preprocessor directive creates symbolic constants called
macro.

– Syntax: #define macro-name replacement

– When the preprocessor encounters this directive, it replaces any


occurrence of macro in the rest of the code by replacement before the
program compiled.

45
Contd.
• e.g.,

46
Contd…
• Output:

47
Contd…
• The #include directive:
– When the preprocessor finds an # include directive it replaces the header
by the entire content of the specified header file or file.

– To include headers provided by the implementation use the following


syntax:
• #include<header>

– To include a file use the following syntax:


• #include “file”

48
Scope Resolution operator(::)

• The scope resolution (::) operator is used to qualify hidden names

so that you can still use them.

• a namespace scope or global scope name is hidden by the

declaration of the same name in a block.

49
Contd..
• E.g.,

50
Namespace
• Namespaces allow to group entities like classes, objects and functions under a
name.
• In this way the global scope can be divided in "sub-scopes", each one with its
own name.
• The purpose of namespace is to localize a name of identifiers to get rid of
naming conflicts across different modules designed by different members of
programming team.
• Syntax for defining Namespace:
– namespace namespace_name
{
entities; // declaration of variables, functions, classes, etc
}
51
Contd..
• For example:
– namespace myNamespace

int a, b; // scope of variable a and b is within this namespace only

 In order to access these variables from outside the myNamespace


namespace we have to use the scope resolution operator :: as follows:

– myNamespace::a

– myNamespace::b

52
Contd..
• Example1:

53
Contd..
• Repeated use of variable in the name space

54
Contd..
• Repetitive use of namespace name can be eliminated by including the
namespace in the source file as:
– Syntax: using namespace namespace_name;

– Example:

55
Contd..
• Including the specific component from the name space as:
– Syntax: Using namespace_name::component_name

– Example:

56
Note the following fact about the namespace:
• We can define namespace with the same namespace name which has already
been used.

• Nesting namespace: Namespaces can be nested as:

– namespace outer

{ entities;

namespace inner

entities;

}}

• Name space Aliases: shorter names can be assigned to namespaces as,

– E.g., namespace oi = outer:: inner;


57
Contd..
• Example2:

58
Input/ Output stream(cin and cout)
• C++ uses a convenient abstraction called streams (a flow of data)
to perform input and output operations in sequential media such
as the screen, the keyboard or a file.

• The standard library defines a handful of stream objects that can


be used to access what are considered the standard sources and
destinations of characters by the environment where the program
runs:

– cout

– cin

59
Contd..
• The output with cout:

– On most program environments, the standard output by default


is the screen, and the C++ stream object defined to access it is
cout.

– For formatted output operations, cout is used together with the


insertion operator(<<).

– The << operator inserts the data that follows it into the stream
object that precedes it.

– For example: in the statement cout<<“Welcome!”; the <<


operator directs the string constant “Welcome” to cout, which
sends it for the display to the monitor. 60
Contd..
• E.g.,

61
Contd…
• Output:

62
Contd..
• Cascading of insertion operator(<<):
– Multiple insertion operations (<<) can be chained in a single
statement to direct a series of output stream to the cout
object.

– The streams are directed form left to right.

– For example: In the statement cout<<“sum =“<<x+y; the


string “sum =“ will be directed first and then the value of x+y.

63
Contd..
• E.g.,

64
Contd..
• Output:

65
Contd..
• Input with cin:
– In most program environments, the standard input by default is the
keyboard, and the C++ stream object defined to access it is cin.
– For formatted input operations, cin is used together with the extraction
operator(>>).
– This operator is then followed by the variable where the extracted data is
stored.
– The >> operator extracts the value from the stream object cin in its left and
place to the variable on its right.
– For example: In the statement cin>> a; The >> operator extracts the value
from cin object that is entered form the keyboard and assigns it to the
variable a.
66
Contd..
• E.g.,

67
Contd..
• Output:

68
Contd..
• Cascading of extraction (>>) operator:

– Multiple extraction operations (>>) can be chained in a single


statement to extract a series of input stream from the cin object.

– The streams are extracted and values are assigned form left to right.

– For example: In the statement cin>>l>>b; , the first value entered


will be assigned to the variable l and the second value entered will
be assigned to variable b.

69
Contd..
• E.g.,:

70
Contd..
• Output:

71
Contd..
• Example Program: to convert temperature in Fahrenheit to
celsius

72
Contd..
• Output:

73
Manipulators
• Manipulators are operators used in C++ for formatting output.
The data is manipulated by the programmer’s choice of display.
• There are numerous manipulators available in C++. Some of the
more commonly used manipulators are:
– endl
– setw

• To be able to use manipulators in our program, we must include


<iomanip> header file in our source program.
• But here is an exception – the endl manipulator can be used
without including the <iomanip> file.

74
Contd..
• The endl manipulator:
– It has same effect as using the newline character ‘\n’.

– but additionally clears the output buffer also.

– For example: The statement

cout<<"First value="<< first<<endl<< "second value= "<<second;

Will cause two lines of output.

75
Contd..
• Program:

76
Contd..
• Output:

77
Contd..
• The setw manipulator:

– This manipulator causes the output stream that follows it to be printed

within a field of n characters wide, where n is the argument to setw.

– The output is right justified with in the field.

– If we do not use setw, the output is left justified by default and it occupies

the space in the monitor equal to number of characters in it.

78
Control statements
• Not many programs execute all their statements in strict order from
beginning to end.

• Most programs decide what to do in response to changing circumstances.

• The flow of control jumps from one part of the program to another,
depending on calculations performed in the program.

• Program statements that cause such jumps are called control statements.

• There are three major categories:

– decisions/selection/branching statements

– loops/ iterations/repetitions statements and

– Jumps statements

79
Decisions(Selection structures)
• This structures makes one-time decision, causing a one-
time jump to a different part of the program, depending
on the value of an expression.

• In C++ program decisions can be made in two ways:


– By using If statements : chooses between two alternatives.
– By using switch statements: creates branches for multiple
alternative sections of code, depending on the value of a
single variable.

80
Contd..
• The if statements:

– Syntax:

if (testExpression)

// statements

81
Contd..
• How if statement works?

82
Contd..
• Example Program:
output1

output2

83
Contd..
• The if...else statements:
– Syntax:

• If(testExpression)

//statements

else

//statements

84
Contd..
• How if...else statement works?

85
Contd..
• Example program:

86
Contd..
• The Nested if…else statements:
• Syntax:
if (testExpression1)
{
// statements to be executed if testExpression1 is true
}
else if(testExpression2)
{
// statements to be executed if testExpression1 is false and testExpression2 is true
}
else if (testExpression 3)
{
// statements to be executed if testExpression1 and testExpression2 is false and testExpression3 is true
}
..
else
{
// statements to be executed if all test expressions are false
} 87
Contd..
• Example program:

88
Contd..
• The switch statements: When a case constant is found that
matches the switch expression, control of the program passes to
the block of code associated with that case.
– Syntax:
switch (n)
​{
case constant1:
// code to be executed if n is equal to constant1;
break;
case constant2:
// code to be executed if n is equal to constant2;
break;
...
default:
// code to be executed if n doesn't match any constant
}
89
Contd..
• How switch statements works?

90
Contd..
• Example:

91
Contd..
• Output:

92
Loops(Iteration statements)
• Loops cause a section of your program to be repeated a certain
number of times. The repetition continues while a condition is
true. When the condition becomes false, the loop ends and
control passes to the statements following the loop.

• There are three kinds of loops in C++:


– For loop

– While loop and

– Do…while loop

93
Contd..
• The For loops:
– Syntax:

for(initializationStatement; testExpression; updateStatement)

// codes

Note: where, only testExpression is mandatory.

94
Contd..
• How for loops works?

95
Contd..
• Example program:

96
Contd..
• The while loop:
– Syntax:
while (testExpression)

// codes

where, testExpression is checked on each entry of the while loop.

97
Contd..
• How while loop works?

98
Contd..
• Example program:

99
Contd..
• The do…while loop:
– The do...while loop is a variant of the while loop with one important
difference. The body of do...while loop is executed once before the test
expression is checked.
– The syntax of do..while loop is:
do

// codes;

} while (testExpression);

100
Contd..
• How do...while loop works?

101
Contd..
• Example program:

102
Contd..
• Output:

103
Jump statements

• Jump statements are used to transfer control of a program

execution from one part of the program to another.

• C++ supports the following jump statements:

– The break statement

– The continue statement

– The goto statement

– The return statement

104
Contd..
• The break statement:

– The use of break statement causes the immediate termination


of the switch statement and the loop from the point of break
statement.

– The control then passes to the statements following the switch


statement and the loop.

105
Contd..
• E.g.,:

106
Contd..
• The Continue statements:

– The continue statement causes the program to skip the rest of

the loop in the current iteration, as if the end of the statement

block had been reached, causing it to jump to the start of the

following iteration.

107
Contd..
• E.g.,

108
Contd..
• Example2:

109
Contd..
• Output:

110
Contd..
• The goto statement:

– It allows making an absolute jump to another point in the program.

– The destination point is identified by a label, which is then used as

an argument for the goto instruction.

– The label is made of a valid identifier followed by a colon(:).

111
Contd..
• Example:

112
Contd..
• Output:

113
Contd..
• The return statement:
– It is used to transfer the program control back to the caller of
the method.

114
Functions
• In programming, function refers to a segment that groups code to
perform a specific task.

• Depending on whether a function is predefined or created by


programmer; there are two types of function:

– Library Function

– User-defined Function

115
User-defined Function
• C++ allows programmer to define their own function.

• A user-defined function groups code to perform a specific task and that group

of code is given a name(identifier).

• When the function is invoked from any part of program, it all executes the

codes defined in the body of function.

116
Contd..
• How C++ functions works?

117
Contd..
• For Example:

118
Default Argument
• When declaring a function we can specify a default value for each of

the last parameters which are called default arguments.

• If a value for that parameter is not passed when the function is called,

the default value is used, but if a value is specified this default value is

ignored and the passed value is used instead.

119
Contd..
• For Example:

Output:

120
Inline Function
• We make a function if the same operation is to be repeated at different
location of the program.

• Functions save the memory space as all the calls to the function cause
the same code to be executed.

• But, calling a function increases the execution time overhead.

• One possible way to reduce such overhead by copying a code at the


point of call.
• Such copying of a code can be achieved by making a function inline.

121
Contd..
• If a function is inline, the compiler places a copy of the code of that function
at each point where the function is called at compile time.

• The compiler can ignore the inline qualifier in case defined function is more
complex(e.g., contains loop).

• To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function.

• Syntax of Inline Function


inline return_type function_name (argument list)

// body of function

122
Contd..
• For example 1:

Output:

123
Contd..
• Example 2: Inline function

124
Contd..
• Advantages of inline function:

– No function call overhead, therefore execution of the program

becomes faster than using normal functions.

– Better error checking is performed as compared to macros.

– Can access members of a class which can not be done with

macros.

125
Contd..
• Disadvantages of inline function:
– If the function call is made repeatedly, object code size increases and thus
requires more memory at the time of execution.

– The compiler can not perform inlining if the function is too complicated.

126
Function overloading
• Function Overloading is a mechanism that allows a single

function name to be used for different functions in a program.

• Two or more functions having same name but different

arguments (i.e., different signature) are known as overloaded

functions.

– E.g.,:

• display(int)

• display(float)
127
Contd..
• Functions can be overloaded in two ways:
– Function overloading with different types of arguments

– Function overloading with different number of arguments

128
Contd..
• Function overloading with different types of arguments:
• When we need to have same operation on different types of
variables, we overload the functions with different type of
arguments.

• The following example illustrates this concept:

129
Contd..
• For Example:

130
Contd..
• Function overloading with different number of arguments
– As in type of argument, overloading can be done with the number
of arguments.

– As the name is same the compiler differentiates the function with


the number of arguments.

– Following example illustrates this concept:

131
Contd..
• For example:

132
Contd..
• Output:

133
Passing arguments to the function
• Three ways to pass arguments to the function (Types of function
call):
– Pass by value

– Pass by reference

– Pass by pointer

134
Contd..
• Pass by value: Copies of the arguments are passed of the function not the
variables themselves.

• Example:

135
Contd..
• Pass By reference: In case of pass by reference, address of the
variable(i.e., variable itself) not copies of the arguments are passed to the
function.

• Example:

136
Contd..
• Pass by pointer:

– Working principle of pass by pointer is same as the pass by

reference.

– Only the difference is that instead of using the reference

variable we use the pointer variable in function definition and

pass address of the variable from the function call statement.

137
Contd..
• Example:

138
Returning form Function
• Three way to return value form one function to another function.
– Return by value

– Return by reference

– Return by pointer

139
Contd..
• Return By value: When a value is returned a copy of that value is returned to
the caller form the called function.

140
Contd..
• Return by reference: when a variable is returned by reference, a
reference to the variable is passed back to the caller.

• Example:

141
Contd..
• Return By pointer: Returns the address of the variable.

• Example:

142
Scope/Visibility and Storage class
• Scope (Visibility):
– scope of a variable determines which part of the program
can access it.

– There are three types of variable scope:


• Local scope

• Global scope(file scope)

• Class scope

143
Contd..
• Local Scope: A variable declared within a block of code
enclosed by braces({ }) is accessible only within that block, and
only after the point of declaration. Outside that they are
unavailable.

• Global scope: Any variable declared outside all blocks has global
scope. It is accessible anywhere in the file after its declaration.

• Class scope: In general members of classes have class scope.(we


will discuss in detail later). 144
Contd..
• Example:

145
Contd..
• Output:

146
Contd..
• Storage Class:
– Every variable has two features: type and storage class.

– Type specifies the type of data that can be stored in a variable.


For example: int, float, char etc.

– And, storage class controls two different properties of a


variable: lifetime (determines how long a variable can exist)
and scope (determines which part of the program can access
it).
147
Contd..
• There are five types of storage classes of C++. They
are:
• Automatic

• External

• Static

• Register

• Mutable

148
Contd..
• Automatic Storage Class:
– The keyword auto is used to declare automatic variables(or local
variables).
• Syntax: auto int var;

– However, if a variable is declared without any keyword inside a


function, it is automatic by default.
– The scope of automatic variable is only limited to the function
where it is defined
– The life of a automatic variable ends (It is destroyed) when the
function exits.

149
Contd..
• Example:

150
Contd..
• Output:

151
Contd..
• Example: scope and life of global variable is entire program

152
Contd..
• Output:

153
Contd..

• External Storage class:

– The keyword extern is used to declare external variable.

– The extern modifier is most commonly used when there are two or more

files sharing the same global variables.

– When you have multiple files and you define a global variable , which will

be used in other files also, then extern will be used in another file to give

reference of defined variable .

154
Contd..
• Example: Mul.cpp file to illustrate external storage class

155
Contd..
• Example: Mul.cpp file to illustrate external storage class

156
Contd..
• Output:

157
Contd..
• Static storage class:
– Keyword static is used for specifying a static variable.
– For example:
int main()
{
static float a;
... .. ...
}
– A static local variable exists only inside a function where it is declared
(similar to a local variable) but its lifetime starts when the function is called
and ends only when the program ends.
– The main difference between local variable and static variable is that, the
value of static variable persists the end of the program.
158
Contd..
• Example:

159
Contd..
• Output:

• Output of above program if var was not specified as static variable:

160
Contd..
• Register storage class:
– Keyword register is used for specifying register variables.
• Syntax: register datatype var_name1 [= value];

– Register variables are similar to automatic variables and exists inside a


particular function only. It is supposed to be faster than the local variables.

– If a program encounters a register variable, it stores the variable in


processor's register rather than memory if available. This makes it faster
than the local variables.

– However, this keyword was deprecated in C++11 and should not be used.

161
Contd..
• Mutable storage class:

– In C++, a class object can be kept constant using


keyword const. This doesn't allow the data members of the
class object to be modified during program execution. But,
there are cases when some data members of this constant
object must be changed.

– In those cases, we can make these variables modifiable using


a mutable storage class.

– Syntax: mutable datatype var_name1;

162
Pointers
• A pointer is a variable whose value is the address of another

variable.

• Pointers are used in C++ program to access the memory and

manipulate the address.

• Pointers solve two common software problems:

– Pointers allow different sections of code to share information easily.

– Pointers enable to build complex linked data structures like linked lists

trees , etc.
163
Contd..
• Pointer variables declaration:
– Like any variable, you must declare a pointer before you can work
with it.

– The general form of a pointer variable declaration is :


• Syntax: type *var-name; // pointer variable is declared by placing * before the variable name.

– Where,
• type is the data type pointed to by the pointer. This type is not the type of

the pointer itself, but the type of the data the pointer points to.

• Var_name = name of pointer variable (should be valid identifier)

• asterisk (*) used when declaring a pointer only means that it is a pointer

164
Contd..
• For Example:
– int *ip; // pointer to an integer

– double *dp; // pointer to a double

– float *fp; // pointer to a float

– char *ch // pointer to character

– The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that the
pointer points to.
165
Contd..

• When declaring multiple pointer variable of same type on the

same line then * must be preceded in each variable as:

– Int * p1, *p2;

• Int * p1, p2; // declares p1 as pointer variable and p2 as a normal

variable

166
Contd..
• Pointer initialization:
– Pointers can be initialized either to the address of a variable , or to the
value of another pointer(or array):
– Pointer initialization to the address of a variable:
• For example:
int myvar;
int * myptr = &myvar;
– Pointer initialization to the value of another pointer:
• For example:
int myvar;
int *f = &myvar;
int *bar = f;

167
Contd..
• Operators in Pointers:
– Reference operator (&)/address-of and

– Deference operator (*)/ value at the address

168
Contd..
• Reference operator (&)/address-of and:
– The address of a variable can be obtained by preceding the
name of a variable with an ampersand sign (&), known
as address-of operator.
– For example: int a =10;
int *p = &a; //pointer declaration and initialization
int b = a; // value of a is assigned to b so, b = 10
– This would assign the address of variable a to pointer variable
p, we are no longer assigning the content of the variable itself
to p, but its address..
169
Contd..
• Dereference operator (*):
– An interesting property of pointers is that they can be used to access the
variable they point to directly. This is done by preceding the pointer name
with the dereference operator (*). The operator itself can be read as "value
pointed to by".

– For example: int x = *p;

– This could read as x equal to value pointed by p, and the statement would
actually assign the value of 10 to x

170
Contd..
• Example1:

171
Contd..
• Output:

172
Contd..
• Example2:

173
Contd..
• Output:

174
Contd..
• Pointers and Arrays:
– The concept of arrays is related to that of pointers. In fact, arrays
work very much like pointers to their first elements, and, actually,
an array can always be implicitly converted to the pointer of the
proper type.

– For example, consider these two declarations:

• int x[20];

• int* p;

– Now the following assignment operation is valid:

• p =x;
175
Contd..
• After that, p and x would be equivalent and would have very
similar properties.

• The main difference being that p can be assigned a different


address, whereas x can never be assigned anything, and will
always represent the same block of 20 elements of type int.

• Therefore, the following assignment would not be valid:


– x= p;

176
Contd..
• Example:

177
Contd..
• Output:

• Note: Pointers and arrays support the same set of operations, with the same
meaning for both. The main difference being that pointers can be assigned
new addresses, while arrays cannot.

178
Contd..
• Passing Array to a Function in C++:

– C++ does not allow to pass an entire array as an argument to a


function.

– However, You can pass a pointer to an array by specifying the


array's name without an index.
• E.g., display(marks);

– To pass a array as an argument in a function declare function


formal parameter in one of following three ways:

179
Contd..
• Way-1 :Formal parameters as a pointer as follows −
void myFunction(int *param)
{
………
……..
….. . .
}

180
Contd..

• Way-2:Formal parameters as a sized array as follows :

void myFunction(int param[10])

...

…..

…….

181
Contd..
• Way-3: Formal parameters as an unsized array as follows :

void myFunction(int param[])

{
...

…..

…..

}
182
Contd..
• Example1:

183
Contd..
• Output:

184
Contd..
• Example2:

185
Contd..
• Output:

186
Contd..
• Example3:

187
Contd..
• Output:

188
Contd..
• Example: passing 2-D Array to function

189
Contd..
• Output:

190
Dynamic Memory Allocation with new and delete
• Arrays can be used to store multiple homogenous data but there are serious
drawbacks of using arrays.

• You should allocate the memory of an array when you declare it but most of
the time, the exact memory needed cannot be determined until runtime.

• The best thing to do in this situation is to declare an array with maximum


possible memory required (declare array with maximum possible size
expected).

• The downside to this is unused memory is wasted and cannot be used by any
other programs.

• To avoid wastage of memory, you can dynamically allocate memory required


during runtime using new and delete operator in C++.

191
Contd..
• Operators new and new[]
– Dynamic memory is allocated using operator new.

– new is followed by a data type specifier and, if a sequence of


more than one element is required, the number of these within
brackets [].

– It returns a pointer to the beginning of the new block of


memory allocated

192
Contd..
– Its syntax is:
pointer = new type
pointer = new type [number_of_elements]

The first expression is used to allocate memory to contain one


single element of type type.

– The second one is used to allocate a block (an array) of


elements of type type, where number_of_elements is an
integer value representing the amount of these.

193
Contd..
– For example:

int * p;

p = new int [5];

– In this case, the system dynamically allocates space for five


elements of type int and returns a pointer to the first element
of the sequence, which is assigned to p (a pointer).
Therefore, p now points to a valid block of memory with
space for five elements of type int.

194
Contd..
• Operators delete and delete[]
• In most cases, memory allocated dynamically is only needed during specific
periods of time within a program; once it is no longer needed, it can be freed
so that the memory becomes available again for other requests of dynamic
memory. This is the purpose of operator delete, whose syntax is:
delete pointer;

delete[] pointer;

• The first statement releases the memory of a single element allocated


using new, and the second one releases the memory allocated for arrays of
elements using new and a size in brackets ([]).

195
Contd..
• Example:

196
Contd..
• Output

197
Thank You !

198

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy