KEMBAR78
UNIT - I Notes | PDF | Object Oriented Programming | C++
0% found this document useful (0 votes)
69 views48 pages

UNIT - I Notes

Uploaded by

yaminisreeja03
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)
69 views48 pages

UNIT - I Notes

Uploaded by

yaminisreeja03
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/ 48

CS305PC: OBJECT ORIENTED PROGRAMMING USING C++

​ B.TECH II Year I Sem. L T P C


2 0 0 2
Prerequisites: A course on “Programming for Problem Solving using C”.

Course Objectives:
​ Introduces Object Oriented Programming concepts using the C++ language.
​ Introduces the principles of data abstraction, inheritance and polymorphism;
​ Introduces the principles of virtual functions and polymorphism
​ Introduces handling formatted I/O and unformatted I/O
​ Introduces exception handling

Course Outcomes:
​ Able to develop programs with reusability
​ Develop programs for file handling
​ Handle exceptions in programming
​ Develop applications for a range of problems using object-oriented programming techniques

UNIT - I
Object-Oriented Thinking: Different paradigms for problem solving, need for OOP paradigm,
differences between OOP and Procedure oriented programming, Overview of OOP concepts-
Abstraction, Encapsulation, Inheritance and Polymorphism.
C++ Basics: Structure of a C++ program, Data types, Declaration of variables, Expressions,
Operators, Operator Precedence, Evaluation of expressions, Type conversions, Pointers, Arrays,
Pointers and Arrays, Strings, Structures, References. Flow control statement- if, switch, while, for, do,
break, continue, goto statements. Functions - Scope of variables, Parameter passing, Default
arguments, inline functions, Recursive functions, Pointers to functions. Dynamic memory allocation
and de-allocation operators-new and delete, Preprocessor directives.

UNIT - II
C++ Classes and Data Abstraction: Class definition, Class structure, Class objects, Class scope,
this pointer, Friends to a class, Static class members, Constant member functions, Constructors and
Destructors, Dynamic creation and destruction of objects, Data abstraction, ADT and information
hiding.

UNIT - III
Inheritance: Defining a class hierarchy, Different forms of inheritance, Defining the Base and Derived
classes, Access to the base class members, Base and Derived class construction, Destructors, Virtual
base class.
Virtual Functions and Polymorphism: Static and Dynamic binding, virtual functions, Dynamic
binding through virtual functions, Virtual function call mechanism, Pure virtual functions, Abstract
classes, Implications of polymorphic use of classes, Virtual destructors.

UNIT - IV
C++ I/O: I/O using C functions, Stream classes hierarchy, Stream I/O, File streams and String
streams, Overloading operators, Error handling during file operations, Formatted I/O.

UNIT - V
Exception Handling: Benefits of exception handling, Throwing an exception, The try block, Catching
an exception, Exception objects, Exception specifications, Stack unwinding, Rethrowing an exception,
Catching all exceptions.
TEXT BOOKS:
1. The Complete Reference C++, 4th Edition, Herbert Schildt, Tata McGraw Hill.
2. Problem solving with C++: The Object of Programming, 4th Edition, Walter Savitch,
Pearson Education.

REFERENCES:
1. The C++ Programming Language, 3rd Edition, B. Stroutstrup, Pearson Education.
2. OOP in C++, 3rd Edition, T. Gaddis, J. Walters and G. Muganda, Wiley Dream Tech Press.
3. Object Oriented Programming in C++, 3rd Edition, R. Lafore, Galigotia Publications Pvt
Ltd.
UNIT - I
Object-Oriented Thinking:
Different paradigms for problem solving:
Paradigm: A method to solve a problem.
Programming paradigm: It is an approach to solve problem using programming language,
tools & techniques. It can be also a methodology/strategy.
Programming paradigm can be broadly classified into types,
1. Imperative programming paradigm
2. Declarative programming paradigm
Let us go, one by one,
1. Imperative programming paradigm
⮚ It performs step by step task by changing state.

⮚ The main focus is on how to achieve a goal.

⮚ This paradigm consists of several statements & after execution all, the
result will be stored,
⮚ It is based on Von-Neuman architecture i.e stored program concept(where
data & programs are stored random access memory(RAM)).
Advantages:
- Simple to implement.
- Consists of loops, variables.
Disadvantages:
- Complex problem can not be solved.
- Less efficient & productive
- Parallel programming is not possible

Ex: C,FORTAN etc.


The Imperative programming paradigm can be further classified into, three types,
i. Procedural programming paradigm
ii. Object-oriented programming
iii. Parallel processing approach
Let us see, one by one,
i. Procedural programming paradigm:
- Importance to procedure or functions.
- Reusability
Ex: C, Coldfusion, Pascal, C++ & Java etc.
ii. Object-oriented programming:
- Importance to data.
- The program is collection of classes & objects.
- The smallest entity is object, on which the computation is
performed.
- It can handle all kind of real-time problems.
- It has a concepts like, Inheritance, Abstraction, Encapsulation,
Polymorphism. These features makes easy to solve complex
problems.
- It ensures data security by principle called data-hiding.
Ex: Simula, Java, C++, Visual Basic.NET, Python, Ruby & Small talk.
iii. Parallel processing approach
- It is the processing of program instructions by dividing them
among multiple processors.
- It is like divide-conqer.
Advantages:
- Takes less time for execution.
Ex: C,C++ & NESL.
2. Declarative programming paradigm:
i. It is a style of building programs that expresses logic of computation.
ii. Also considers programs as theories of some logic.
iii.Simplifies the writing of pararllel programs.
iv. Focus is on what to do(What needs to be done).
v. It declare the result that we want(rather than how it is to be produced).
The Declarative programming paradigm can be classified into following types.
i. Logic programming paradigm
ii. Functional [programming
iii. Database processing approach
Let us see one by one,
i. Logic programming paradigm:
- It is abstract model of computation.
- It solves the problem like puzzles, series etc.
- Here, we have knowledge-base(which is given to machine)
produces result.
- In case of Artificial Intelligence, machine learning, we have
perception model.
- Importance is to knowledge base & the problem.
- The execution of program is like proof of mathematical statements.
Ex: Prolog.
ii. Functional [programming:
- It has roots in mathematical & it is language independent.
- The key is, execution of series of mathematical functions.
- The centre model for abstraction is the function.
- Data are loosely coupled to functions.
- The function hide their implementation.
Ex: Perl, Javascript, Lisp & Haskwell.
iii. Database processing approach:
- It is based on data & its movement.
- Program statements are defined by data.
- A database program is a heart of business information system.
- It provides file creation, data entry, update, query etc.
- The are several programming languages developed for database
application, like SQL(Structured Query Language).
Ex: SQL.-streams of structured data, filtering, transformations &
aggregating(Computing statics) .

Need for OOP paradigm:


⮚ It can handle real-time problems.

⮚ It ensures data-security.
⮚ We can achieve reusability via inheritance feature & also we can remove
redundancy.
⮚ It is flexible.

⮚ It introduces like concepts like, Abstraction, Encapsulation & Polymorphism.

⮚ Dynamic binding(Linking procedures call at run-time).

⮚ Complex problem can be easily solved.

⮚ Here their exists, standard modules using which, we can write programs without
starting from scratch.
⮚ The principle of Data-hiding helps the programmer to build secure programs. Data is
hidden can’t be accessed by external functions.
⮚ It is easy to partition the work based on object.

⮚ Object-oriented systems can be easily upgraded.

⮚ Software complexity can be easily managed.

⮚ We can add data & functions easily.

Differences between OOP and Procedure oriented programming:

Sr.no Procedure-Oriented Language Object-orientedProgramming


Language
1. In procedural programming, In object oriented programming,
program is divided into smallprogram is divided into small
parts called functions. parts called objects.
2. Procedural programming Object oriented programming
follows top down approach. follows bottom up approach.
3. There is no access specifier Object oriented programming
in procedural programming. have access specifiers like
private, public, protected etc.
4. Adding new data and Adding new data and function is
function is not easy. easy.
5. Procedural programming Object oriented programming
does not have any proper provides data hiding so it is more
way for hiding data so it secure.
is less secure.
6. In procedural programming, Overloading is possible in object
Operator overloading is not oriented programming.
possible.
7. In procedural programming, In object oriented programming,
function is more important data is more important than
than data. function.
8. Procedural programming is Object oriented programming is
based on unreal world. based on real world.
9. Examples: C, FORTRAN, Examples: C++, Java, Python, C#
Pascal, Basic etc. etc.

Overview of OOP concepts-


Abstraction, Encapsulation, Inheritance and Polymorphism.

Abstraction:
It refers to the act of representing essential features without including background details.
For example, Car is an abstraction – you don't know internal working of the car but within
car there are subsystems like steering, brake, clutch.
Encapsulation:
The wrapping up of data & functions into a single unit(called class) is known as
encapsulation. The data is not accessible to the outside world, & only those functions those
are wrapped in the class can access it. These functions provide the interface between the
object’s data & the program. The insulation of data from direct access by the program is
called data hiding or information hiding.
Inheritance:
It is the process by which objects of one class acquire the properties of objects of another
class. The principle behind this is that the derived class shares common characteristics with
the class from which it is derived.
The concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a new
class from then existing one. The new class will have the combined features of both classes.
The more real appealing power of the inheritance is that it allows the programmer to
reuse a class. Here each sub class defines only those features that are unique it.

Polymorphism:
It is a Greek term, means the ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of a data
used in the operation.
For ex.: consider the operation of addition. For two numbers, the operation will generate
sum. If the operands are strings, then the operation would produce a third string by
concatenation. The process of making an operator to exhibit different behaviors in different
instances is known as operator overloading.
Below figure illustrates that a single function name can be used to handle different number &
different types of arguments. Using a single function name to perform different types of tasks
is known as function overloading.
C++ Basics:
Structure of a C++ program:
#include<iostream>
using namespace std;
int main()
{
int i;
cout<<”This is output”<<”\n”; //This is single line comment.
/* This is multiline
comment*/
//input a number using >>
cout<<”Enter a number”<<endl;
cin>>i;
//now, output using <<
Cout<<i<<” Squared is = ”<<i*i;
return 0;

}
Output:
This is output
Enter a number
2
2 Squared is = 4
⮚ <iostream> supports C++ style I/O operations.

⮚ using namespace std; this line tells the compiler to use the std namespace.
A namespace is the declarative region in which program elements can be placed.
This using statement informs the compiler that you want to use the std namespace.
⮚ cout<<”This is output”<<”\n”; causes, this is output(to be displayed on the screen ).
<<(left shift operator ), but here it is a output operator.
⮚ cout is an identifier linked to the screen, cout refers to screen.
⮚ //This is single line comment. This is a single line comment whatever // follows is
ignored by compiler. For explanation purpose, we can write comments.
⮚ Multiline comments as in C, in C++ also it can be used.
⮚ cout<<”Enter a number”<<endl; Enter a number will be prompted & endl is a keyword
represents end of a line.
⮚ cin>>i; the number is read from keyboard.
⮚ >> right shift operator, when used here, it is an input operator.
⮚ i reads value from keyboard
⮚ cin refers to the standard input device i.e keyboard.
⮚ The ouput will be printed as,
2 Squared is = 4
⮚ The statement,
return 0; the program return 0 to the calling process(Operating system)
returning 0 indicates that the program terminated normally.
Abnormal termination, should be signaled by non-zero value.
Example programs.
1. Write a C++ program to print Hello message.
#include<iostream>
using namespace std;
int main()
{
cout<<”Hello, Wecome to OOPs with C++ programming ”;
return 0;
}
Output:
Hello, Wecome to OOPs with C++ programming

2. Write a C++ program to add two number.


#include<iostream>
using namespace std;
int main()
{
int a,b,sum;
cout<<”Enter the value of a & b”<<endl;
cin>>a>>b;
sum=a+b;
cout<<”sum=”<<sum;
return 0;
}
Output:
Enter the value of a & b
23
Sum=5
Data Types:

A data type specifies the type of data that a variable can store such as integer, floating,
character etc.

There are 4 types of data types in C++ language.

Types Data Types

Basic Data Type int, char, float, double, etc

Derived Data Type array, pointer, etc

Enumeration Data Type enum

User Defined Data Type structure


Basic Data Types
The basic data types are integer-based and floating-point based. C++ language supports
both signed and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating
system.

Let's see the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range


Char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
Short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
Int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 32,767
short int 2 byte -32,768 to 32,767
signed short int 2 byte -32,768 to 32,767
unsigned short int 2 byte 0 to 32,767
long int 4 byte
signed long int 4 byte
unsigned long int 4 byte
Float 4 byte
Double 8 byte
long double 10 byte

Structures:
⮚ It is a collection of variables under one name.

⮚ It helps in keeping related information together.

⮚ Syntax:
struct struct_type_name
{
Type member_name;
Type member_name;
Type member_name;
.
.
.
}structure_variables;
Example:
Struct addr
{
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int ZIP;
};
⮚ The variables that make up the structure are called members.

⮚ When you a define a structure you are defining compound type.

⮚ To declare a structure variable,


struct addr addr_info;
the addr_info in memory,

Name 30 bytes

street 40 bytes

city 20 bytes

State 3
bytes

ZIP 4 bytes

⮚ addr a_info,b_info,c_info;
can also be declared.
⮚ Accessing structure variables,
addr_info.ZIP=12345;
i.e. structure_name.member_name;
⮚ Structure assignments,
#include<iostream>
using namespace std;
int main()
{
struct xyz
{
int a;
int b;
}x,y;
x.a=10;
x.b=15;
y=x;
cout<<y.a<<y.b;
return 0;
}
Output:
10 15

Declaration of variables:
Variables can be declared in two ways.
i. Local variables
ii. Global variables
Let us see one by one,
i. Local variables: the variable which are local to particular block are
called local variables.
ii. Global variables: The life span of these variables will be until the
program goes of scope.
Example:
#include<iostream>
using namespace std;
int a;//Global variable
int addition(int x,int y);
int main()
{
int b,result;//local variable declaration
cout<<”Enter a & b”;
cin>>a>>b;
result=addition(a,b);
cout<<”sum=”<<result;
return 0;
}
int addition(int x,int y)
{
int sum; //local variable declaration
sum=x+y;
return sum;
}

Type conversions:
⮚ When variables of one type is mixed with another type, a type conversion will occur.

⮚ The value of the right side(expression side) of the assignment is converted to the
type of the left side(target variables).
⮚ Examples:
#include<iostream>
using namespace std;
int main()
{
int x;
char ch;’
float f;

ch=x; // lower order 8 bit will remain same, & higher 8 order will be loss.
x=f;//Non-fractional part will be remained & fractional part will be loss.
f=ch;// converts into float format
f=x;// // converts into float format
return 0;
}

Target Type Expression Type Possible information


loss
signed char char If values 127, target is
negative
char short int Higher order 8 bits
char int(16 bits) Higher order 8 bits
char int(32 bits) Higher order 24 bits
char long int Higher order 24 bits
short int int(16 bits) None
short int int(32 bits) Higher order 16 bits
int(16 bits) long int Higher order 16 bits
int(32 bits) long int none
int float Fractional part
float double Precision result rounded
double long double Precision result rounded

Operator:
There are 4 main classes of operators,
i. Arithmetic operator
ii. Relational operator
iii. Logical operator
iv. Bitwise operator
Let us see one by one,
i. Arithmetic operator:

Operator Action
- Subtraction, unary minus
+ Addition
* Multiplication
/ Division
% Modulus
-- Decrement
++ Increment

Example:
//program to demonstrate arithmetic operators.
#include<iostream>
using namespace std;
int main()
{
int x,y;
x=5;
y=2;
cout<<”x+y=”<<x+y<<”\n”;
cout<<”x-y=”<<x-y<<”\n”;
cout<<”x*y=”<<x*y<<”\n”;
cout<<”x/y=”<<x/y<<”\n”;
cout<<”x%y=”<<x%y<<”\n”;
return 0;
}
Output:’
x+y=7
x-y=3
x*y=10
x/y=2
x%y=1
//program to demonstrate increment & decrement operators.
#include<iostream>
using namespace std;
int main()
{
int x=10;
int z=10, w,y;
y=++x; // sets y=11,x=11
w=z++;//sets w=10, z=11
cout<<”y=”<<y<<”w=”<<w;
return 0;
}
Output:
y=11 w=10

#include<iostream>
using namespace std;
int main()
{
int x=10;
int z=10, w,y;
y=--x; // sets y=9,x=9
w=z--;//sets w=10, z=9
cout<<”y=”<<y<<”w=”<<w;
return 0;
}
Output:
y=9 w=10

Precedence of Arithmetic operators,


Highest ++,--
-(unary minus)
* ,/ ,%
Lowest +,-

ii. Relational operator & Logical operator:


Relational operator: Refers to the relationships that values can have with one
another.
Logical operator: refers to the way these relationships can be connected.
⮚ The idea of true & false underlies these operators,

⮚ In C++, the outcome of a relational or logical operation is true or false.( non-zero or


0).
⮚ Relational operator are,
Operator Action
> Greater than
>= Greater than or equal
< Less than
<= Less than
== Equal
!= Not equal

Logical operator are,


Operator Action
&& AND
II OR
! NOT
The truth table for logical operator is shown below,(using 1’s & 0’s),
P q p&&q pIIq !p
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
The precedence of relational & logical operators are given below,
Highest !
>,>=,<,<=
==,!=
&&
Lowest II

Example,
1. !0 && 0 II 0
1 && 0 II 0
0II0
0
2. !(0 && 0) II 0
!0 II 0
1II0
1

iii. Bitwise operator:


⮚ Operations on bits.

⮚ It refers to testing, setting, or shifting the actual bit in a byte.

Operator Action
& AND
I OR
^ XOR
~ NOT
>> SHIFT RIGHT
<< SHIFT LEFT

p q p&q pIq p^q ~p


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

1. AND
char ch=’A’;
char result=ch & 127;

11000001 <- ‘A’ with parity set


& 01111111 (Bitwise AND)

01000001 <-‘A’ without parity


2. OR
⮚ Reverse of AND

⮚ Can be used to set a bit.


10000000 <-128 in binary
I 00000011<-3 in binary

10000011 <-result
3. XOR
⮚ A bit set off the bits being compared are different.
01111111<-127 in binary
^01111000<-120 in binary

00000111<-result
⮚ Bitwise operations may produce value other than ‘0’ or ‘1’.

⮚ While logical operators will always evaluate to ‘0’ & ‘1’.


4. Shift right & shift left operator.
value>>number of bit positions; // right shift
value<<number of bit positions; // left shift

ex:
x=7 00000111 7
x=x<<1 00001110 14
y=12 00001100 12
y=y>>1 00000110 6

iv. The ternary operator:


⮚ Substitute for if-then-else.
Exp1?Exp2:Exp3;
Ex: x=10;
Y=x>9?100;200;

It is similar to,
x=10
if(x>9)
x=100;
else
x=200;
v. The ‘&’ and ‘*’ pointer operator.
‘&’ operator:
⮚ It is a unary operator i.e it operates on single operand.

⮚ It returns the memory address of an operand.

⮚ Ex: m=&count;
&->address of
‘*’ operator:
⮚ It is complement of ‘&’.

⮚ It is also a unary operator that returns the value of the variable.


Ex: q=*m; // value at m.
// program to demonstrate ‘&’ and ‘*’ operator.
#include<iostream>
using namespace std;
int main()
{
int target,source;
int *m;
source=10;
m=&source;
target=*m;
cout<<”target=”<<target;
return 0;
}
Output:
target=10
vi. sizeof operator:
⮚ sizeof is a unary compile-time operator that returns the length, in
bytes, of the variable or parenthesized type-specifies that it precedes.

Ex: double f;
cout<<sizeof f;
cout<<sizeof (int);
output:
84
vii. the comma operator:
⮚ the comma operator combines together several expressions.

⮚ The expression at right side become, the total value of the


comma-separated expression.
Ex:
x=(y=3,y+1);
x=4;
viii. The dot(.) & arrow (->) operators:
⮚ . (dot), -> (arrow) operator access individual elements of structure &
union.
⮚ In C++, the dot operator is used to when working with structure.

⮚ The arrow operator is used when a pointer to structure is used.


EX:
struct employee
{
char name[80];
int age;
float wage;
} emp;
struct employee *p;
p=&emp;
emp.wage=123.23;
Or
p->wage=123.23;
ix. The [ ] and () operator:
⮚ (), parenthesis are operator that increase the precedence of the
operations inside them.
⮚ [ ], square bracket performs array indexing.
⮚ The expression within array bracket [ ] provides an index into that
array.
Ex:
#include<iostream>
using namespace std;
char S[80];
int main()
{
S[3]=’X’;
cout<<S[3];
return 0;
}
Operator precedence:

Highest ( ), [ ], ->, .
!,~,++,--,*, &,sizeof
*,/,%
+,-
<<,>>
<,<=,>,>=
==,!=
&
^
I
&&
II

Highest ?:
Lowest =,+=,-=,*=,/=

Expressions:
i. Constant expressions
ii. Integral expressions
iii. Float expressions
iv. Pointer expressions
v. Relational expressions
vi. Logical expressions
vii. Bitwise expressions
Let us see one by one,

i. Constant expressions:
Expression consists of constants.
EX:
15
20+15/2.0
‘x’
ii. Integral expressions
These expression produce integer values,
Ex:
m
m*n-5
m*’x’
5+int(2.0) // here m & n are integers
iii. Float expressions
It produces floating point results.
Ex:
x+y
x*y/10 //here, x y are floating point variables
5+float(10)
10.75
iv. Pointer expressions:
These expressions produces address values.
&m //m is a variable
ptr
ptr+1 //ptr is a pointer
v. Relational expressions:
These expressions yields the result either true or false.’
Ex:
x<=y
a+b==c+d
m+n>100
vi. Logical expressions:
It combines two to more relational expressions & produce bool type results.
Ex:
a>b && x==10
x==10 II y==5
vii. Bitwise expressions:
⮚ These are used to manipulate data at bit level.

⮚ Used for testing or shifting bits.


EX:
x<<3
y>>1
Evaluation of expressions
1. 10-3%8+6/4
10-3%8+6/4
10-3+6/4
10-3+1
7+1
8
2. 17-8/4*2+3-++5
17-8/4*2+3-++5
17-8/4*2+3-6
17-2*2+3-6
17-4+3-6
13+3-6
16-6
10
3. -3+2*3-3/4+2
-3+2*3-3/4+2
-3+6-3/4+2
-3+6-0+2
3-0+2
3+2
5
Arrays
- It is a collection of variables of the same type that are referred
through a common name.
- A specific element in an array is accessed by an index.
- Array may have one, to several dimensions.
Single dimension array:
Syntax:
type var_name[size];
- This is array declaration. From this compiler allocate space for
them in memory.
- Type is base type of the array, which is the type of each element in
the array.
- size, how many elements array can hold.
Ex.: double balance[100];
- the array element accessing by indexing the array name.
balance[3]=12.23;
ex. char p[10];
we are declaring a character array that has ten elements, p[0]
through p[9].
#include<iostream>
using namespace std;
int main()
{
int x[100];
int t;
for(t=0;t<100;++t) // load x with values ‘0’ through ‘99’.
x[t]=t;
for(t=0;t<100;++t)
cout<<x[t];
return 0;
}
- the amount of storage required to hold an array is directly to its
type & size.
Total bytes=sizeof(base type)*size of array
- single-dimension arrays are essentially lists of information of the
same type are stored in contiguous memory location in index order
Ex.: char a[7];
If memory location starts at 1001,

Element a[0] a[1] a[2] a[3] a[4] a[5] a[6]


address 1001 1002 1003 1004 1005 1006 1007

Two dimension Arrays,


- It is an array of one-dimension arrays.
- To declare integer array ‘d’ of size 10,20
int d[10][20];
- To access, point 1,2 of array ‘d’, you would use, d[]1[2].
- Ex.:
#include<iostream>
using namespace std;
int main()
{
int t,i,num[3][4];
for(t=0;t<3;++t)
for(i=0;i<4;++i)
num[t][i]=(t*4)+i+1;
// now print them
for(t=0;t<3;++t)
for(i=0;i<4;++i)
cout<<”%3d”,num[t][i];
cout<<”\n”;
return 0;
}
num[3][4]
1 2 3 4
5 6 7 8
9 10 11 12
- Below figure, for a graphic represented of a two-dimensional array
in memory.
- Char ch[4][3];
ch[0][0] ch[0][1] ch[0][2]
ch[1][0] ch[1][1] ch[1][2]
ch[2][0] ch[2][1] ch[2][2]
ch[3][0] ch[3][1] ch[3][2]

- In 2-D array, the number of bytes of memory needed,


Bytes=size of first index*size of second index*size of base type.
=4*3*1
=12
Multi-dimension Array:
Syntax:
type name[size1][size2]……[size N];
Pointers:
- There are 3 reasons, why have to use pointers.
i. Pointers provide the means by which function can modify
their calling arguments.
ii. Pointers support dynamic allocation.
iii. Pointers can improve the efficiency of certain routines.
What are pointers?
- It is a variable which stores the address of another variable.

Pointer variable:
- Syntax:
- type *name;
Pointer operator: (‘*’ and ‘&’)
int *m;
int count,q;
m=&count; // ‘m’ points to count
q=*m;
Pointer assignments:
#include<iostream>
using namespace std;
int main()
{
int x;
int *p1,*p2;
p1=&x;
p2=p1;
cout<<p2;
return 0;
}
Output:
Prints address of x
Pointer Arithmetic:
int *p1;
p1++;
p1--;
p1=p1+12;

Operations on pointers:
- Pointers can be incremented, decremented and also two pointers
can be subtracted.
- You may add or subtract integers to or from pointers.
- Pointers can not be multiplied, divide pointers.
- We cant add two pointers.
- Pointers can be compared.
Pointers & Arrays:
- There is close relationship between pointers & arrays.
- Ex.:
char str[80], *p1;
p1=str;//p1 has been set to the address of the first array element in
//str
//to access the fifth element,
// using array
str[4]
//using pointer
*(p1+4)
- In C++, there are two methods of accessing array elements.
i. Pointers arithmetic
ii. Array indexing
- Two versions of putstr()
/*Index ‘s’ as an array */
void putstr(char *s)
{
int t;
for(t=0;s[t];++t)
putchar(s[t]);
}
/*Access s as a pointer*/
void putstr(char *str)
{
while(*s)
putchar(*s++);
}
Arrays of Pointers:
- Pointers may be arrayed like any other data type, the declaration
for an int pointer array of size 10 is,
int *x[10];
//To assign variable to third element of the point array
x[2]=&var;
//To find the value of var,
*x[2]
- if you want to pass an array of pointers into to a function.
void display_array(int *q[])
{
int t;
for(t=0;t<10;++t)
cout<<*q[t];
}
References:
- It is a feature related to the pointer.
- A reference variable can be created with ‘&’ operator.
- It is a reference for existing variable.
Ex.:
string food=”pizza”; //food variable
string &meal=food; //reference to food
cout<<food<<”\n”;
cout<<meal<<”\n”;
- Call by reference can be achieved by two ways
i. You can explicitly pass a pointer to the argument.
ii. You can use a reference parameter.
i. #include<iostream>
using namespace std;
void neg(int *i);
int main()
{
int x;
x=10;
cout<<x<<”negted is”;
neg(&x);
cout<<x<<”\n”;
return 0;
}
void neg(int *i)
{
*i=-*i;
}
ii. Use a reference parameter
#include<iostream>
using namespace std;
void neg(int &i); // ‘i’ now a reference
int main()
{
int x;
x=10;
cout<<x<<”negated is”;
neg(x); //no longer need the ‘&’ operator.
cout<<x<<”\n”;
return 0;
}
void neg(int &i)
{
i=-i; // ‘i’ is now a reference.
}

C++ strings:
- Most common use of the one dimensional array is as a character
string.
- C++ supports two types of strings
i. Null terminated strings
ii. Also defines a string class.
- i. The first is the null terminated string contains the character
array.(A null is zero)
- Thus a null terminated string contains the character that comprise
the string followed by a null.(C string)
- ii. C++ also defines a string class called, string, which provides an
object-oriented approach to string handling.
- When declaring a character array that will hold a null-terminated
string, you need to declare it to be one character longer than the
largest string that it is to hold.
- For ex. To declare an array str that can hold a 10 character string,
you would write
char str[11]; //this makes room for the null at the end of string
- When you use a quoted string constant in your program, you are
also creating a null terminated string.
- A string constant is a list of characters enclosed in double quotes.
- For ex.
“hello there”
You do not need to add the null to the end of string constants
manually – the compiler does this for automatically.
C++ supports a wide range of functions that manipulate
null-terminated strings.
The most common are,

Name Function
strcpy(s1,s2) Copies s2 into s1
strcat(s1,s2) Concatenates s2 onto the end of s1
strlen(s1) Returns the length of s1
strcmp(s1,s2) Returns 0 if s1 & s2 are same; less than
0 if s1<s2; greater than 0 if s1>s2.
strchr(s1,ch) Returns a pointer to the first occurrence
of ch in s1.
strstr(s1,s2) Returns a pointer to the first occurrence
of s2 in s1.
- These functions use the header file string.h also <cstring>.
- The following program illustrates the use of these string functions,
#include<iostream>
#include<string>
int main()
{
char s1[80],s2[80];
gets(s1);
gets(s2);
cout<<”Length of s1 & s2 is=”<<strlen(s1)<<strlen(s2);
if(!strcmp(s1,s2))
cout<<”The strings are equal”<<endl;
strcat(s1,s2);
cout<<s1<<endl;
strcpy(s1,”This is a test”);
cout<<s1<<endl;
if(strchr(“hello”,’e’))
cout<<”e is in hello \n”;
if(strstr(“hi there”,”hi”))
cout<<”found hi”<<endl;
return 0;
}
If you run this program & enter the strings “hello” & “hello”, the
output is,

Length of s1 & s2 is= 5 5


The strings are equal
hellohello
This is a test
e is in hello
found hi
C++ strings:
- It is a collection of characters surrounded by double quotes.
- Ex.: string greeting=”Hello”;
- To use string, we need to include the header file, <string>
- String concatenation,
- string firstName=”Jhon”;
string lastName=”Doe”;
string fullName=firstName+lastName;
cout<<fullName;
String length:
- there exist a built in method length() using which we find the length
of string.
- Ex.:
String txt=”ABCDE”;
Cout<<”The length of txt string is ”<<txt.length();
Access strings:
- String myString=”Hello”;
cout<<myString[0];
it outputs H.
user input string:
string firstName;
cout<<”Type your first name”;
cin>>firstName;
cout<<”Your name is :”<<firstName;

output:
Type your first name: John
Your name is : John

Flow control statements:


if, switch, while, for, do-while, break, continue, goto statements.

C++ if-else
In C++ programming, if statement is used to test the condition. There are various types
of if statements in C++.

o if statement
o if-else statement
o nested if statement
o if-else-if ladder

C++ IF Statement
The C++ if statement tests the condition. It is executed if condition is true.

​ if(condition){
​ //code to be executed
​ }

C++ If Example
​ #include <iostream>
​ using namespace std;

​ int main () {
​ int num = 10;
​ if (num % 2 == 0)
​ {
​ cout<<"It is even number";
​ }
​ return 0;
​ }
​ Output:
​ It is even number

C++ IF-else Statement


The C++ if-else statement also tests the condition. It executes if block if condition is true
otherwise else block is executed.

​ if(condition){
​ //code if condition is true
​ }else{
​ //code if condition is false
​ }

C++ If-else Example


​ #include <iostream>
​ using namespace std;
​ int main () {
​ int num = 11;
​ if (num % 2 == 0)
​ {
​ cout<<"It is even number";
​ }
​ else
​ {
​ cout<<"It is odd number";
​ }
​ return 0;
​ }
Output:
It is odd number
C++ IF-else-if ladder Statement
The C++ if-else-if ladder statement executes one condition from multiple statements.

​ if(condition1){
​ //code to be executed if condition1 is true
​ }else if(condition2){
​ //code to be executed if condition2 is true
​ }
​ else if(condition3){
​ //code to be executed if condition3 is true
​ }
​ ...
​ else{
​ //code to be executed if all the conditions are false
​ }

C++ If else-if Example


​ #include <iostream>
​ using namespace std;
​ int main () {
​ int num;
​ cout<<"Enter a number to check grade:";
​ cin>>num;
​ if (num <0 || num >100)
​ {
​ cout<<"wrong number";
​ }
​ else if(num >= 0 && num < 50){
​ cout<<"Fail";
​ }
​ else if (num >= 50 && num < 60)
​ {
​ cout<<"D Grade";
​ }
​ else if (num >= 60 && num < 70)
​ {
​ cout<<"C Grade";
​ }
​ else if (num >= 70 && num < 80)
​ {
​ cout<<"B Grade";
​ }
​ else if (num >= 80 && num < 90)
​ {
​ cout<<"A Grade";
​ }
​ else if (num >= 90 && num <= 100)
​ {
​ cout<<"A+ Grade";
​ }
​ }
​ Output:
​ 1. Enter a number to check grade:66
​ C Grade
​ 2. Enter a number to check grade:-2
​ wrong number

C++ switch
The C++ switch statement executes one statement from multiple conditions. It is like
if-else-if ladder statement in C++.

​ switch(expression){
​ case value1:
​ //code to be executed;
​ break;
​ case value2:
​ //code to be executed;
​ break;
​ ......

​ default:
​ //code to be executed if all cases are not matched;
​ break;
​ }

C++ Switch Example


​ #include <iostream>
​ using namespace std;
​ int main () {
​ int num;
​ cout<<"Enter a number to check grade:";
​ cin>>num;
​ switch (num)
​ {
​ case 10: cout<<"It is 10";
​ break;
​ case 20: cout<<"It is 20";
​ break;
​ case 30: cout<<"It is 30";
​ break;
​ default: cout<<"Not 10, 20 or 30";
​ break;
​ }
​ }
​ Output:
​ 1. Enter a number:
​ 10
​ It is 10
​ 2. Enter a number:
​ 55
​ Not 10, 20 or 30
C++ For Loop
The C++ for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop than while or do-while loops.

The C++ for loop is same as C/C#. We can initialize variable, check condition and
increment/decrement value.

​ for(initialization; condition; incr/decr){


​ //code to be executed
​ }

C++ For Loop Example


​ #include <iostream>
​ using namespace std;
​ int main() {
​ for(int i=1;i<=10;i++){
​ cout<<i <<"\t";
​ }
​ }
​ Output:
​ 1 2 3 4 5 6 7 8 9 10

C++ While loop


In C++, while loop is used to iterate a part of the program several times. If the number
of iteration is not fixed, it is recommended to use while loop than for loop.

​ while(condition){
​ //code to be executed
​ }

C++ While Loop Example


Let's see a simple example of while loop to print table of 1.

​ #include <iostream>
​ using namespace std;
​ int main() {
​ int i=1;
​ while(i<=10)
​ {
​ cout<<i <<"\t";
​ i++;
​ }
​ }
​ Output:
​ 1 2 3 4 5 6 7 8 9 10

C++ Do-While Loop


The C++ do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.

The C++ do-while loop is executed at least once because condition is checked after loop
body.

​ do{
​ //code to be executed
​ }while(condition);

C++ do-while Loop Example


Let's see a simple example of C++ do-while loop to print the table of 1.

​ #include <iostream>
​ using namespace std;
​ int main() {
​ int i = 1;
​ do{
​ cout<<i<<"\t";
​ i++;
​ } while (i <= 10) ;
​ }
​ Output:
​ 1 2 3 4 5 6 7 8 9 10
C++ Break Statement
The C++ break is used to break loop or switch statement. It breaks the current flow of the
program at the given condition. In case of inner loop, it breaks only inner loop.

​ jump-statement;
​ break;

C++ Break Statement Example


Let's see a simple example of C++ break statement which is used inside the loop.

​ #include <iostream>
​ using namespace std;
​ int main() {
​ for (int i = 1; i <= 10; i++)
​ {
​ if (i == 5)
​ {
​ break;
​ }
​ cout<<i<<"\n";
​ }
​ }
​ Output:
​ 1
​ 2
​ 3
​ 4

C++ Continue Statement


The C++ continue statement is used to continue loop. It continues the current flow of
the program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

​ jump-statement;
​ continue;

C++ Continue Statement Example


​ #include <iostream>
​ using namespace std;
​ int main()
​ {
​ for(int i=1;i<=10;i++){
​ if(i==5){
​ continue;
​ }
​ cout<<i<<"\t";
​ }
​ }
​ Output:
​ 1 2 3 4 6 7 8 9 10

C++ Goto Statement


The C++ goto statement is also known as jump statement. It is used to transfer control
to the other part of the program. It unconditionally jumps to the specified label.

It can be used to transfer control from deeply nested loop or switch case label.

C++ Goto Statement Example


Let's see the simple example of goto statement in C++.

​ #include <iostream>
​ using namespace std;
​ int main()
​ {
​ ineligible:
​ cout<<"You are not eligible to vote!\n";
​ cout<<"Enter your age:\n";
​ int age;
​ cin>>age;
​ if (age < 18){
​ goto ineligible;
​ }
​ else
​ {
​ cout<<"You are eligible to vote!";
​ }
​ }
​ Output:
​ You are not eligible to vote!
​ Enter your age:
​ 16
​ You are not eligible to vote!
​ Enter your age:
​ 7
​ You are not eligible to vote!
​ Enter your age:
​ 22
​ You are eligible to vote!

Functions :
- It is a set of instructions which performs desired, specific
task.
Scope of variables:
-Scope refers to the to the visibility of variables.
-In other words, which part of your program can see or use
it.
i. Local variables
ii. Global variables,
// CPP program to illustrate scope of local & global variables.
#include<iostream>
using namespace std;
int global=5;
int main()
{
int global=2;
cout<<global<<endl;
return 0;
}
Output:
2

Ex. 2:
#include<iostream>
using namespace std;
// Global x
int x=0;
int main()
​ {
​ //local x
​ int x=10;
​ cout<<”value of global x is :”<<::x;
​ cout<<”value of local x is :”<<x;
​ return 0;
​ }
Output:
Value of global x is : 0
Value of local x is : 10

Parameter passing:
#include<iostream>
using namespace std;
void swap(int a,int b);
int main()
{
int x,y;
cout<<”Enter x, y”;
cin>>x>>y;
swap(x,y); //passing parameter x,y
return 0;
}

​ void swap(int a,int b)


​ {
​ int temp;
​ temp=a;
​ a=b;
​ b=temp;
​ cout<<”a=”<<a<<”b=”<<b;
​ }
Default Arguments:
- C++ allows a functions to assign a parameter a default value when
no argument corresponding to that parameter is specified in a call
to that function.
- The default value is specified in a manner syntactically similar to a
variable initialization.
- For ex.
void myFunc(double d=0.0)
{
//………………..
}
//Function takes double argument with a default value of 0.0
myFunc(198.234); //pass a explicit value
myFunc(); //let function use default
Advanatges of using default arguments
i. Programmer can manage greater complexity.
ii. We can use at both times default & exact times.
//Programs to illustrate default arguments
#include<iostream>
using namespace std;
void clrscr(int size=25);
int main()
{
int i;
for(i=0;i<30;i++)
cout<<i<<endl;
clrscr(); // by default it clears 25 lines
for(i=0;i<30;i++)
cout<<i<<endl;
clrscr(10); //clears 10 lines
return 0;
}
void clrscr()
{
for(;size;size--)
cout<<endl;
}

Inline functions:
- In C++, we can create short functions, that are not actually called,
rather their code is expanded in line at the point of each
invocation.
- It is like macro.
- The function should precede its definition with the inline keyword.
It causes a function to be expanded in line rather than called.
#include<iostream>
using namespace std;
inline int max(int a,int b)
{
return a>b?a:b;
}
int main()
{
cout<<max(10,20);
cout<<” ”<<max(99,88);
return 0;
}
- inline function allow you create very efficient code.
- When function is called, a significant overhead is generated by the
calling & return mechanism.
- Arguments are pushed to the stack & registers are saved when the
function is called & restored when the function returns.
- The problem is that these instruction takes time.
- When function is expanded, no such operation occur.
- It produce faster run times.
- It is best to inline only very small function.
- It is also good idea to inline only those functions that will have
significant impact on the performance of your program.
Recursive Functions:
- A function can call itself.
- A function is said to be recursive, if a statement in the body of the
function calls itself.
- Recursion is the process of defining something in terms of itself.
Ex:
int fact(int n)
{
int answer;
if(n==1)
return 1;
answer=fact(n-1)*n;
return(answer);
}
Ex:
fact(5)
fact(4)*5
fact(3)*4*5
fact(2)*3*4*5
fact(1)*2*3*4*5
1*2*3*4*5=120

Pointers to Functions
- Even though a function is not a variable, it still has a physical location in memory that
can be assigned to a pointer.
- This address is the entry point of the function & it is the address used when the
function is called.
- Once a pointer points to a function, the function can be called through that pointer.
- Function pointer also allow functions to be passed as arguments to other functions.
- We can obtain the address of a function name without any parentheses or
arguments.(similar to the way an array’s address is obtained when only the array
name, without index is used)

Ex:1)
#include<iostream>
using namespace std;
int Add(int a,int b)
{
return a+b;
}
int main()
{
int c;
int (*p)(int,int); //pointers to functions
//pointers to function that should take (int,int) as argument or parameter
//returns int
p=&Add;
c=(*p)(2,3); //de-referencing & executing the function
cout<<c;
return 0;
}
Output:
5
In above example,
Instead of writing,
p=&Add;
we can also write,
p=Add; //Function name will return pointers
Also, instead of writing, c=(*p)(2,3);
We can also wirte, c=p(2,3); //de-referencing, executing the function.
Output,
5
Ex:2)
#include<iostream>
using namespace std;
void PrintHello()
{
Cout<<”Hello \n”;
}
void PrintHello(char *name)
{
cout<<”Hello”<<name;
}
int main()
{
void (*p)();
p=PrintHello; // p points to PrintHello function
p();
void (*ptr)(char *);
ptr=PrintHello;
ptr(“Tom”);
return 0;
}
Output:
Hello
Hello Tom

Dynamic memory allocation & de-allocation operator using new & delete:
- C++ provides two dynamic allocation operator: new & delete.
- These operator are used to allocate & free memory at run time.
- Dynamic allocations is an important part of almost all real-world
programs.
- C++ also supports dynamic memory allocation functions called,
malloc() & free().
- The new operator allocates memory & returns a pointer to the start
of it.
- The delete operator frees memory previously allocated using new.
- The general form of new & delete are,
p_var=new type;
delete p_var;
here, p_var is a pointer variable that receives a pointer to memory
that is large enough to hold an item of type.
- On new operator failure, it returns null.
//here is a program that allocates memory to hold an integer.
#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int;
*p=100;
cout<<”At”<<p<<””;
cout<<”is the value”<<*p<<endl;
delete p;
return 0;
}
- This program assigns to p and address in the heap that is large
enough to hold an integer.
- It then assigns that memory the value 100 & displays the content
of the memory on the screen.
- Finally, it frees the dynamically allocated memory by delete
operator.
- New & delete perform functions similar to malloc() & free(), but
they have several advantages.
i. new allocates memory automatically of specified type. We
need not use sizeof operator because, the size is
computed automatically.
ii. new automatically returns a pointer of the specified
type.(you need not use explicit type cast as you when
allocating memory by using malloc()).
Initializing Allocated Memory:
- you can initialize allocated memory to some known value by
putting an initializer after the type name in the new statement.
- Here, is the general form of new when an initialization is included,
p_var=new var_type(initializer);
//this program gives the allocated integer an initial value of 87.
#include<iostream>
using namespace std;
int main()
{
int *p;
p=new int(87);
cout<<”At”<<p<<” ”;
cout<<”is the value”<<*p<<”\n”;
delete p;
return 0;
}
Allocating Arrays:
- We can allocate memory for arrays using new operator,
p_var=new array_type[size];
here, size specifies the number of elements in the array.
- To free an array, use this form of delete.
delete [] p_var;
here, the [] informs delete that an array is being released.
// The below program allocates 10 element integer array.
#include<iostream>
using namespace std;
int main()
{
int *p,i;
p=new int[10]; //allocates 10 integer array.
for(i=0;i<10;i++)
p[i]=i;
for(i=0;i<10;i++)
cout<<p[i]<<” ”;
delete [] p; //releases the array
return 0;

Pre-processor Directives:
- Pre-processor directives instructions to compiler. Preprocessor are
programs that process our source code before compiles.
- The pre-processor contains the following diterctives.
#define #elif #else #endif
#error #if #ifdef #ifndef
#include #line #pragma #undef
- All pre-processor begins with ‘#’ symbol.
Let us one by one,
i. #define
The general form of the directive is,
Ex.1 #define LEFT 1
#define RIGHT 0
cout<<RIGHT<<LEFT+1;
output:
02
Ex.2 #define ONE 1
#define TWO ONE+ONE
#define THREE ONE+TWO
Output:
cout<<ONE<<TWO<<THREE;
output:
123
Ex.3 #define E_MS “Standard error on input \n”
cout<<E_MS;
Output:
Standard error on input
Ex.4 #define MAX_SIZE 10
float balance[MAX_SIZE];
for(i=0;i<MAX_SIZE;i++)
cout<<balance[i];
for(i=0;i<MAX_SIZE;i++)
x+=balance[i];
ii. #error
- The #error directive forces the compiler to stop compilation.
- It is used for primarily for debugging.
- The general form of the #error directive is
#error error_message
- When the #error directive is encountered, the error message is
displayed. Along with the other information defined by compiler.
iii. #include
- The #include directive instructs the compiler to read another
source file in addition to the that contains the #include directive.
For ex.:
#include<iostream>
- Include files can have #include directives in them. This is referred
to as nested includes.
- Standard C++ recommends that the at least 256 levels of nesting
be supported.
- In addition to files, a C++ program can use the #include directive
to include directive a C++ header.
- C++ defines a set of standard header that provide the information
necessary to the various libraries.
- A header is simply an abstraction that guarantees that the
appropriate information required by your program is included.

Conditional Compilation Directives:


- These are several directives that allow you to selectively compile
portions of your programs source code. This process is called
conditional compilation.
- #if, #else, #eif, and #endif
i. The general form of #if is
#if constant-expression
Statement sequence
#endif
Ex:
#include<iostream>
#define MAX 100
using namespace std;
int main()
{
#if MAX>99
cout<<”Compiled for array greater than 99 \n”;
#endif
return 0;
}
ii. The #else directive works much like the else that is part of the C++ language.
Ex.:
#include<iostream>
#define MAX 10
int main()
{
#if MAX>99
cout<<”Compiled for value greater than 99 \n”;
#else
Cout<<”compiled for small value”;
#endif
return 0;
}
iii. The #elif
- The #elif directive means “else if” & establishes an if-else-if chain
for multiple compilation options.
- The general form for #elif is
#if expression
Statement sequence
#elif expression1
Statement sequence
#elif expression2
Statement sequence
#elif expression3
Statement sequence
-
-
-
-
#elif expression N
Statement sequence
#endif
Ex. The following fragment uses the value of ACTIVE_COUNTRY
to define the currency sign.
#define US 0
#define ENGLAND 1
#define JAPAN 2
#define ACTIVE_COUNTRY US
#if ACTIVE_COUNTRY==US
char currency[]=”dollar”;
#elif ACTIVE_COUNTRY==ENGLAND
char currency[]=”pound”;
#else
char currency[]=”yen”;
#endif
- Standard C++ suggests that at least 256 levels of nesting be
allowed.

iv. ifdef and #ifndef


- it is defined & if not defined
- the general form of #ifdef is
#ifdef macro_name
Statement sequence
#endif
- the macro name defined in a #define statement.
- The general form of #ifdef is,
#ifndef macro_name
Statement sequence
#endif
Fro ex.:
#include<iostream>
#define TED 10
using namespace std;
int main()
{
#ifdef TED
cout<<”Hi Ted \n”;
#else
cout<<”Hi anyone \n”;
#endif
#ifndef RALPH
cout<<”RALPH not defined \n”;
#endif
return 0;
}
Output:
Hi Ted
RALPH not defined

v. #undef
- The #undef directive removes a previously defined definition of
the macro name that follow it.
- The general form for #undef is
#undef macro_name
For ex.:
#define LEN 100
#define WIDTH 100
char array[LEN][WIDTH];
#undef LEN
#undef WIDTH
/* At this point both LEN & WIDTH are undefined*/

vi. using defined


- in addition to #ifdef, there is a second way to determine if a macro
name is defined.
- You can use #if directive in conjunction with the defined
compile-time operator.
- The defined operator has this general form,
defined macro_name
macro_name is currently defined, then the expression is true other
it is false.
Ex.:
To determine if type macro MYFILE is defined,
#if defined MYFILE
OR
#ifdef MYFILE
Ex.:
#if !defined DEBUG
Cout<<”Final version \n”;
#endif
vii. #line
- This directive changes the contents of __LINE__ & __FILE__.
- The __LINE__ contains the line number of the currently compiled
line of code.
- The __FILE__ identifies is a string that contains the name of the
source file being compiled.
- The general form for #line is
#line number “filename”
Number is any positive integer & becomes the new value of
__LINE__ & the filename is the value of __FILE__.
Ex.
#include<iostream>
#line 100
int main() // line no.100
{ // line no. 101
cout<<__LINE__; // line no. 102
return 0;
}
Output:
102

You might also like