0% found this document useful (0 votes)
13 views102 pages

C, Unit-1

C++ notes

Uploaded by

ssuryaarun5
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)
13 views102 pages

C, Unit-1

C++ notes

Uploaded by

ssuryaarun5
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/ 102

C++

Unit-1
Introduction to C++;

C++ is a general-purpose programming language that was developed as an


enhancement of the C language to include object-oriented paradigm. It is an
imperative and a compiled language.
1. C++ is a high-level, general-purpose programming language designed for
system and application programming. It was developed by Bjarne
Stroustrup at Bell Labs in 1983 as an extension of the C programming
language. C++ is an object-oriented, multi-paradigm language that
supports procedural, functional, and generic programming styles.
One of the key features of C++ is its ability to support low-level, system-level programming, making it
suitable for developing operating systems, device drivers, and other system software. At the same time,
C++ also provides a rich set of libraries and features for high-level application programming, making it a
popular choice for developing desktop applications, video games, and other complex applications.

2. C++ has a large, active community of developers and users, and a wealth
of resources and tools available for learning and using the language.
Some of the key features of C++ include:
3. Object-Oriented Programming: C++ supports object-oriented
programming, allowing developers to create classes and objects and to
define methods and properties for these objects.
4. Templates: C++ templates allow developers to write generic code that
can work with any data type, making it easier to write reusable and
flexible code.
5. Standard Template Library (STL): The STL provides a wide range of
containers and algorithms for working with data, making it easier to
write efficient and effective code.
6. Exception Handling: C++ provides robust exception handling capabilities,
making it easier to write code that can handle errors and unexpected
situations.
Overall, C++ is a powerful and versatile programming language that is
widely used for a range of applications and is well-suited
well suited for both low-level
low
system programming and high level application development.
high-level

Here are some simple C++ code examples


examples to help you understand
the language:

1.Hello World:
C++

#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}

Output
Hello, World!

level language rendering it the advantage of programming


C++ is a middle-level
low-level higher level applications (games, GUI,
level (drivers, kernels) and even higher-level
desktop apps etc.). The basic syntax and code structure of both C and C++
are the same.
Some of the features & key-points to note about the programming language
are as follows:
 Simple: It is a simple language in the sense that programs can be broken
down into logical units and parts, has a rich library support and a variety
of data-types.
 Machine Independent but Platform Dependent: A C++ executable is not
platform-independent (compiled programs on Linux won’t run on
Windows), however they are machine independent.
 Mid-level language: It is a mid-level language as we can do both systems-
programming (drivers, kernels, networking etc.) and build large-scale
user applications (Media Players, Photoshop, Game Engines etc.)
 Rich library support: Has a rich library support (Both standard ~ built-in
data structures, algorithms etc.) as well 3rd party libraries (e.g. Boost
libraries) for fast and rapid development.
 Speed of execution: C++ programs excel in execution speed. Since, it is a
compiled language, and also hugely procedural. Newer languages have
extra in-built default features such as garbage-collection, dynamic typing
etc. which slow the execution of the program overall. Since there is no
additional processing overhead like this in C++, it is blazing fast.
 Pointer and direct Memory-Access: C++ provides pointer support which
aids users to directly manipulate storage address. This helps in doing
low-level programming (where one might need to have explicit control
on the storage of variables).
 Object-Oriented: One of the strongest points of the language which sets
it apart from C. Object-Oriented support helps C++ to make maintainable
and extensible programs. i.e. Large-scale applications can be built.
Procedural code becomes difficult to maintain as code-size grows.
 Compiled Language: C++ is a compiled language, contributing to its
speed.
Here are some key points to keep in mind while working with
C++:

1. Object-Oriented Programming: C++ is an object-oriented programming


language, which means that it allows you to define classes and objects to
model real-world entities and their behavior.
2. Strong Type System: C++ has a strong type system, which means that
variables have a specific type and that type must be respected in all
operations performed on that variable.
3. Low-level Access: C++ provides low-level access to system resources,
which makes it a suitable choice for system programming and writing
efficient code.
4. Standard Template Library (STL): The STL provides a large set of pre-
written algorithms and data structures that can be used to simplify your
code and make it more efficient.
5. Cross-platform Compatibility: C++ can be compiled and run on multiple
platforms, including Windows, MacOS, and Linux, making it a versatile
language for developing cross-platform applications.
6. Performance: C++ is a compiled language, which means that code is
transformed into machine code before it is executed. This can result in
faster execution times and improved performance compared to
interpreted languages like Python.
7. Memory Management: C++ requires manual memory management,
which can lead to errors if not done correctly. However, this also
provides more control over the program’s memory usage and can result
in more efficient memory usage.
8. Syntax: C++ has a complex syntax that can be difficult to learn, especially
for beginners. However, with practice and experience, it becomes easier
to understand and work with.
These are some of the key points to keep in mind when working with C++.
By understanding these concepts, you can make informed decisions and write
effective code in this language.
Applications of C++:
C++ finds varied usage in applications such as:
 Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu
etc.)
 Browsers (Chrome & Firefox)
 Graphics & Game engines (Photoshop, Blender, Unreal-Engine)
 Database Engines (MySQL, MongoDB, Redis etc.)
 Cloud/Distributed Systems

Advantages of C++:

1. Performance: C++ is a compiled language, which means that its code is


compiled into machine-readable code, making it one of the fastest
programming languages.
2. Object-Oriented Programming: C++ supports object-oriented
programming, which makes it easier to write and maintain large,
complex applications.
3. Standard Template Library (STL): The STL provides a wide range of
algorithms and data structures for working with data, making it easier to
write efficient and effective code.
4. Machine Independent: C++ is not tied to any hardware or processor. If
the compiler compiles the program in the system, it will be able to run no
matter what the hardware is.
5. Large Community: C++ has a large, active community of developers and
users, providing a wealth of resources and support for learning and using
the language.

Disadvantages of C++:

1. Steep Learning Curve: C++ can be challenging to learn, especially for


beginners, due to its complexity and the number of concepts that need
to be understood.
2. Verbose Syntax: C++ has a verbose syntax, which can make code longer
and more difficult to read and maintain.
3. Error-Prone: C++ provides low-level access to system resources, which
can lead to subtle errors that are difficult to detect and fix.
Some interesting facts about C++:
Here are some awesome facts about C++ that may interest you:
1. The name of C++ signifies the evolutionary nature of the changes from C.
“++” is the C increment operator.
2. C++ is one of the predominant languages for the development of all kind
of technical and commercial software.
3. C++ introduces Object-Oriented Programming, not present in C. Like
other things, C++ supports the four primary features of OOP:
encapsulation, polymorphism, abstraction, and inheritance.
4. C++ got the OOP features from Simula67 Programming language.
5. A function is a minimum requirement for a C++ program to run.(at least
main() function)

Key concept of objects in C++;

Object-oriented programming – As the name suggests uses objects


in programming. Object-oriented programming aims to implement
real-world entities like inheritance, hiding, polymorphism, etc. in
programming. The main aim of OOP is to bind together the data and
the functions that operate on them so that no other part of the code
can access this data except that function.
There are some basic concepts that act as the building blocks of
OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing
Characteristics of an Object-Oriented
Programming Language

Class
The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds
its own data members and member functions, which can be
accessed and used by creating an instance of that class. A class is
like a blueprint for an object. For Example: Consider the Class of
Cars. There may be many cars with different names and brands but
all of them will share some common properties like all of them will
have 4 wheels, Speed Limit, Mileage range, etc. So here, the Car is
the class, and wheels, speed limits, and mileage are their properties.
 A Class is a user-defined data type that has data members and
member functions.
 Data members are the data variables and member functions are
the functions used to manipulate these variables together these
data members and member functions define the properties and
behavior of the objects in a Class.
 In the above example of class Car, the data member will be
speed limit, mileage, etc and member functions can apply brakes,
increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group
of objects which shares some common properties and behaviors.
Object
An Object is an identifiable entity with some characteristics and
behavior. An Object is an instance of a Class. When a class is
defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated.
C++

// C++ Program to show the syntax/working of Objects as a


// part of Object Oriented PProgramming
#include <iostream>
using namespace std;

class person {
char name[20];
int id;

public:
void getdetails() {}
};

int main()
{

person p1; // p1 is a object


return 0;
}
Objects take up space in memory and have an associated address
like a record in pascal or structure or union. When a program is
executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects
can interact without having to know details of each other’s data or
code, it is sufficient to know the type of message accepted and the
type of response returned by the objects.
To know more about C++ Objects and Classes, refer to this article –
C++ Classes and Objects
Encapsulation
In normal terms, Encapsulation is defined as wrapping up data and
information under a single unit. In Object-Oriented Programming,
Encapsulation is defined as binding together the data and the
functions that manipulate them. Consider a real-life example of
encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. The finance
section handles all the financial transactions and keeps records of all
the data related to finance. Similarly, the sales section handles all
the sales-related activities and keeps records of all the sales. Now
there may arise a situation when for some reason an official from the
finance section needs all the data about sales in a particular month.
In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales
section and then request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single
name “sales section”.

Encapsulation in C++
Encapsulation also leads to data abstraction or data hiding. Using
encapsulation also hides the data. In the above example, the data of
any of the sections like sales, finance, or accounts are hidden from
any other section.
To know more about encapsulation, refer to this article –
Encapsulation in C++
Abstraction
Data abstraction is one of the most essential and important features
of object-oriented programming in C++. Abstraction means
displaying only essential information and hiding the details. Data
abstraction refers to providing only essential information about the
data to the outside world, hiding the background details or
implementation. Consider a real-life example of a man driving a car.
The man only knows that pressing the accelerator will increase the
speed of the car or applying brakes will stop the car but he does not
know how on pressing the accelerator the speed is actually
increasing, he does not know about the inner mechanism of the car
or the implementation of an accelerator, brakes, etc. in the car. This
is what abstraction is.
 Abstraction using Classes: We can implement Abstraction in
C++ using classes. The class helps us to group data members
and member functions using available access specifiers. A Class
can decide which data member will be visible to the outside world
and which is not.
 Abstraction in Header files: One more type of abstraction in
C++ can be header files. For example, consider the pow() method
present in math.h header file. Whenever we need to calculate the
power of a number, we simply call the function pow() present in
the math.h header file and pass the numbers as arguments
without knowing the underlying algorithm according to which the
function is actually calculating the power of numbers.
To know more about C++ abstraction, refer to this article –
Abstraction in C++
Polymorphism
The word polymorphism means having many forms. In simple words,
we can define polymorphism as the ability of a message to be
displayed in more than one form. A person at the same time can
have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person possesses different
behavior in different situations. This is called polymorphism. An
operation may exhibit different behaviors in different instances. The
behavior depends upon the types of data used in the operation. C++
supports operator overloading and function overloading.
 Operator Overloading: The process of making an operator
exhibit different behaviors in different instances is known as
operator overloading.
 Function Overloading: Function overloading is using a single
function name to perform different types of tasks. Polymorphism
is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some
integers, sometimes there are 2 integers, and sometimes there are 3
integers. We can write the Addition Method with the same name
having different parameters, the concerned method will be called
according to parameters.
Polymorphism in C++

To know more about polymorphism, refer to this article –


Polymorphism in C++
Inheritance
The capability of a class to derive properties and characteristics from
another class is called Inheritance. Inheritance is one of the most
important features of Object-Oriented Programming.
 Sub Class: The class that inherits properties from another class
is called Sub class or Derived Class.
 Super Class: The class whose properties are inherited by a sub-
class is called Base Class or Superclass.
 Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class
that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base
Class.

Inheritance in C++

To know more about Inheritance, refer to this article – Inheritance in


C++
Dynamic Binding
In dynamic binding, the code to be executed in response to the
function call is decided at runtime. C++ has virtual functions to
support this. Because dynamic binding is flexible, it avoids the
drawbacks of static binding, which connected the function call and
definition at build time.
Example:
C++
// C++ Program to Demonstrate the Concept of Dynamic binding
// with the help of virtual function
#include <iostream>
using namespace std;

class GFG {
public:
void call_Function() // function that call print
{
print();
}
void print() // the display function
{
cout << "Printing the Base class Content" << endl;
}
};
class GFG2 : public GFG // GFG2 inherit a publicly
{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content"
<< endl;
}
};
int main()
{
GFG geeksforgeeks; // Creating GFG's object
geeksforgeeks.call_Function(); // Calling call_Function
GFG2 geeksforgeeks2; // creating GFG2 object
geeksforgeeks2.call_Function(); // calling call_Function
// for GFG2 object
return 0;
}

Output
Printing the Base class Content
Printing the Base class Content

As we can see, the print() function of the parent class is called even
from the derived class object. To resolve this we use virtual
functions.
Above Example with virtual Function:
C++

#include<bits/stdc++.h>
using namespace std;

class GFG {
public:
void call_Function() // function that call print
{
print();
}
virtual void print() // using "virtual" for the display function
{
cout << "Printing the Base class Content" << endl;
}
};
class GFG2 : public GFG // GFG2 inherit a publicly
{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content"
<< endl;
}
};
int main()
{
GFG geeksforgeeks; // Creating GFG's object
geeksforgeeks.call_Function(); // Calling call_Function
GFG2 geeksforgeeks2; // creating GFG2 object
geeksforgeeks2.call_Function(); // calling call_Function
// for GFG2 object
return 0;
}

//this code is contributed by Md Nizamuddin

Output
Printing the Base class Content
Printing the Derived class Content
Message Passing
Objects communicate with one another by sending and receiving
information. A message for an object is a request for the execution
of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function, and the
information to be sent.
Example:
C++

#include <iostream>
using namespace std;

// Define a Car class with a method to display its speed


class Car {
public:
void displaySpeed(int speed) {
cout << "The car is moving at " << speed << " km/h." << endl;
}
};

int main() {
// Create a Car object named myCar
Car myCar;

// Send a message to myCar to execute the displaySpeed method


int currentSpeed = 100;
myCar.displaySpeed(currentSpeed);

return 0;
}

//this code is contributed by Md Nizamuddin

Oops advantages ;
OOP stands for Object-Oriented Programming. As you can guess
from it’s name it breaks the program on the basis of the objects in it.
It mainly works on Class, Object, Polymorphism, Abstraction,
Encapsulation and Inheritance. Its aim is to bind together the data
and functions to operate on them.
Some of the well-known object-oriented languages are Objective C,
Perl, Java, Python, Modula, Ada, Simula, C++, Smalltalk and some
Common Lisp Object Standard. Here we are discussing its benefits
on C++.

Benefits of OOP
 We can build the programs from standard working modules that
communicate with one another, rather than having to start writing
the code from scratch which leads to saving of development time
and higher productivity,
 OOP language allows to break the program into the bit-sized
problems that can be solved easily (one object at a time).
 The new technology promises greater programmer productivity,
better quality of software and lesser maintenance cost.
 OOP systems can be easily upgraded from small to large
systems.
 It is possible that multiple instances of objects co-exist without
any interference,
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the
program.
 The principle of data hiding helps the programmer to build secure
programs which cannot be invaded by the code in other parts of
the program.
 By using inheritance, we can eliminate redundant code and
extend the use of existing classes.
 Message passing techniques is used for communication between
objects which makes the interface descriptions with external
systems much simpler.
 The data-centered design approach enables us to capture more
details of model in an implementable form.
While it is possible to incorporate all these features in an OOP, their
importance depends upon the type of project and preference of the
programmer. These technology is still developing and current
products may be superseded quickly.
Developing a software is easy to use makes it hard to build.
Disadvantages of OOP
 The length of the programmes developed using OOP language is
much larger than the procedural approach. Since the programme
becomes larger in size, it requires more time to be executed that
leads to slower execution of the programme.
 We can not apply OOP everywhere as it is not a universal
language. It is applied only when it is required. It is not suitable
for all types of problems.
 Programmers need to have brilliant designing skill and
programming skill along with proper planning because using OOP
is little bit tricky.
 OOPs take time to get used to it. The thought process involved in
object-oriented programming may not be natural for some people.
 Everything is treated as object in OOP so before applying it we
need to have excellent thinking in terms of objects.

Input output in C++;

C++ comes with libraries that provide us with many ways for
performing input and output. In C++ input and output are performed
in the form of a sequence of bytes or more commonly known
as streams.
 Input Stream: If the direction of flow of bytes is from the
device(for example, Keyboard) to the main memory then this
process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e.
from main memory to device( display screen ) then this process is
called output.

Header files available in C++ for Input/Output operations are:


1. iostream: iostream stands for standard input-output stream. This
header file contains definitions of objects like cin, cout, cerr, etc.
2. iomanip: iomanip stands for input-output manipulators. The
methods declared in these files are used for manipulating
streams. This file contains definitions of setw, setprecision, etc.
3. fstream: This header file mainly describes the file stream. This
header file is used to handle the data being read from a file as
input or data being written into the file as output.
4. bits/stdc++: This header file includes every standard library. In
programming contests, using this file is a good idea, when you
want to reduce the time wasted in doing chores; especially when
your rank is time sensitive. To know more about this header file
refer this article.
In C++ after the header files, we often use ‘using namespace std;‘.
The reason behind it is that all of the standard library definitions are
inside the namespace std. As the library functions are not defined at
global scope, so in order to use them we use namespace std. So,
that we don’t need to write STD:: at every line (eg. STD::cout etc.).
To know more refer this article.
The two instances cout in C++ and cin in C++ of iostream class are
used very often for printing outputs and taking inputs respectively.
These two are the most basic methods of taking input and printing
output in C++. To use cin and cout in C++ one must include the
header file iostream in the program.
This article mainly discusses the objects defined in the header
file iostream like the cin and cout.
 Standard output stream (cout): Usually the standard output
device is the display screen. The C++ cout statement is the
instance of the ostream class. It is used to produce output on the
standard output device which is usually the display screen. The
data needed to be displayed on the screen is inserted in the
standard output stream (cout) using the insertion operator(<<).
C++
#include <iostream>

using namespace std;

int main()
{
char sample[] = "GeeksforGeeks";

cout << sample << " - A computer science portal for geeks";

return 0;
}

Output:
GeeksforGeeks - A computer science portal for geeks
In the above program, the insertion operator(<<) inserts the value of
the string variable sample followed by the string “A computer
science portal for geeks” in the standard output stream cout which is
then displayed on the screen.
 standard input stream (cin): Usually the input device in a
computer is the keyboard. C++ cin statement is the instance of
the class istream and is used to read input from the standard
input device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for
reading inputs. The extraction operator extracts the data from the
object cin which is entered using the keyboard.
C++
#include <iostream>
using namespace std;

int main()
{
int age;

cout << "Enter your age:";


cin >> age;
cout << "\nYour age is: " << age;

return 0;
}

Input :
18
Output:
Enter your age:
Your age is: 18
The above program asks the user to input the age. The object cin is
connected to the input device. The age entered by the user is
extracted from cin using the extraction operator(>>) and the
extracted data is then stored in the variable age present on the right
side of the extraction operator.
 Un-buffered standard error stream (cerr): The C++ cerr is the
standard error stream that is used to output the errors. This is
also an instance of the iostream class. As cerr in C++ is un-
buffered so it is used when one needs to display the error
message immediately. It does not have any buffer to store the
error message and display it later.
 The main difference between cerr and cout comes when you
would like to redirect output using “cout” that gets redirected to
file if you use “cerr” the error doesn’t get stored in file.(This is
what un-buffered means ..It cant store the message)
C++
#include <iostream>

using namespace std;

int main()
{
cerr << "An error occurred";
return 0;
}

Output:
An error occurred

 buffered standard error stream (clog): This is also an instance


of ostream class and used to display errors but unlike cerr the
error is first inserted into a buffer and is stored in the buffer until it
is not fully filled. or the buffer is not explicitly flushed (using
flush()). The error message will be displayed on the screen too.
C++
#include <iostream>

using namespace std;

int main()
{
clog << "An error occurred";

return 0;
}

Output:
An error occurred

C++ declarations and control structures;

Control structures in C++ are constructs that allow you to control the flow of
execution within a program. They determine the order in which statements are
executed based on certain conditions or criteria. Control structures enable you
to make decisions, iterate over a set of instructions, and perform different
actions based on specific conditions.

Control structures in C++ can be broadly categorized into three types:


selection structures, iteration structures, and jump structures.

Selection Structures
Selection structures in C++ allow you to make decisions based on certain
conditions. They help in choosing a particular path or branch of execution
based on the evaluation of an expression or variable.
1. if statement

The if statement is a fundamental selection structure in C++. It executes a


block of code if a specified condition is true.

if (condition) {

// Code to be executed if the condition is true

2. if-else statement

The if-else statement extends the functionality of the if statement by


allowing you to execute different code blocks based on the evaluation of a
condition.

if (condition) {

// Code to be executed if the condition is true

} else {

// Code to be executed if the condition is false

3. nested if-else statement

Nested if-else statements are multiple if-else statements nested within each
other. They allow you to perform more complex decision-making by checking
multiple conditions.
if (condition1) {

// Code to be executed if condition1 is true

if (condition2) {

// Code to be executed if condition2 is true

} else {

// Code to be executed if condition2 is false

} else {

// Code to be executed if condition1 is false

Iteration Structures
Iteration structures, also known as loop structures, allow you to repeatedly
execute a block of code as long as a specified condition is true. They are
useful when you need to perform repetitive tasks or iterate over a collection of
items.
1. while loop

The while loop executes a block of code repeatedly as long as a specified


condition is true.

while (condition) {

// Code to be executed

2. do-while loop

The do-while loop is similar to the while loop but with a crucial difference:
it executes the code block at least once before checking the condition.

do {

// Code to be executed

} while (condition);
3. for loop

The for loop provides a compact and structured way to iterate over a range
of values. It consists of three parts: initialization, condition, and
increment/decrement.

for (initialization; condition; increment/decrement) {

// Code to be executed

4. range-based for loop

The range-based for loop is a C++11 feature that simplifies iterating over
elements of a container or a range of values.

for (element : collection) {

// Code to be executed for each element

Jump Structures
Jump structures in C++ allow you to transfer control from one part of the
program to another. They alter the normal sequential flow of execution.
1. break statement

The break statement is used to terminate the execution of a loop or switch


statement. It transfers control to the next statement after the loop or switch.

while (condition) {

if (some_condition) {

break; // Exit the loop

// Code to be executed

}
2. continue statement

The continue statement is used to skip the remaining statements in the


current iteration of a loop and move to the next iteration.

for (int i = 1; i <= 10; i++) {

if (i % 2 == 0) {

continue; // Skip even numbers

// Code to be executed for odd numbers

3. return statement

The return statement is used to terminate the execution of a function and


return a value (if the function has a return type).

int square(int x) {

return x * x;

Error Handling Structures


Error handling structures in C++ are used to handle exceptions and errors that
may occur during program execution. They allow you to gracefully handle
exceptional situations and prevent unexpected program termination.

1. try-catch block
The try-catch block is used to catch and handle exceptions. It consists of a try
block where you place the code that might throw an exception, and one or
more catch blocks that handle specific types of exceptions.

try {

// Code that might throw an exception

} catch (exception_type1 e1) {

// Code to handle exception_type1


} catch (exception_type2 e2) {

// Code to handle exception_type2

} catch (...) {

// Code to handle any other type of exception

In the above code, the try block contains the code that could potentially throw
an exception. If an exception is thrown, the catch blocks are evaluated
sequentially to find a matching exception type. The first matching catch block
is executed, and the program flow continues from there.

Conclusion
Control structures in C++ provide the mechanisms to control the flow of
execution, make decisions, repeat tasks, transfer control, and handle errors.
Understanding and effectively using these control structures is crucial for
writing robust and flexible programs.

By utilizing selection structures, you can make decisions based on specific


conditions. Iteration structures enable you to repeat tasks or iterate over data.
Jump structures allow you to transfer control and alter the normal flow of
execution. Error handling structures help in gracefully handling exceptions and
errors.

By combining and nesting these control structures, you can create complex
program flows and solve a wide range of programming problems. It’s
important to choose the appropriate control structure for each situation and
understand their syntax and usage.

Take the time to experiment with control structures in C++ and explore their
capabilities. Practice using them in different scenarios to become comfortable
with their usage and leverage their power to write efficient and robust code.
Remember that good programming practices involve writing code that is clear,
concise, and maintainable. Use meaningful variable names, provide proper
indentation, and include comments to enhance the readability of your code.

Control structures are powerful tools in your programming arsenal. Mastering


them will allow you to write more sophisticated and flexible programs that can
handle a variety of situations and produce reliable and efficient results.

Decision making and statements in C++:

Decision-making in C++ involves the usage of conditional


statements (also called decision control statements) to execute
specific blocks of code primarily based on given situations and their
results.
So basically, in decision-making, we evaluate the conditions and
make a decision about which part of the code should be executed or
not. It allows selective code execution which is crucial for controlling
the flow of a program and making it more dynamic.
Types of Decision-Making Statements in C++
In C++, the following decision-making statements are available:
1. if Statement
2. if-else Statement
3. if-else-if Ladder
4. Nested if Statement
5. switch Statement
6. Conditional Operator
7. Jump Statements: break, continue, go, return
1. if in C++
In C++, the if statement is the simplest decision-making statement. It
allows the execution of a block of code if the given condition is true.
The body of the ‘if’ statement is executed only if the given condition
is true.
Syntax of if in C++
if (condition) {
// code to be executed if the condition is true
}
Here if the condition is true then the code inside the if block will be
executed otherwise not.
Flowchart of if in C++
Example of if in C++
The below example demonstrates the use of the if statement by
finding if the age of a person is greater than 18 or not. if the
condition is true then he/she is allowed to vote.
 C++

// C++ program to find if the age of a person id


greater

// than 18 or not

#include <iostream>

using namespace std;

int main()

int age = 19;

if (age > 18) {

cout << "allowed to vote" << endl;

return 0;

}
Output
allowed to vote

2. if-else in C++
The if-else decision-making statement allows us to make a decision
based on the evaluation of a given condition. If the given condition
evaluates to true then the code inside the ‘if’ block is executed and in
case the condition is false, the code inside the ‘else’ block is
executed.
Syntax of if-else in C++
if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}
Flowchart of if-else in C++

Flow diagram of if else

Example of if-else in C
The below example demonstrates the use of an if-else statement to
find if the given number is positive or nonpositive.
 C++

// C++ program to find if the given number is


positive or

// non positive
#include <iostream>

using namespace std;

int main()

int num = 5;

// Using if-else to determine if the number


is positive

// or non positive

if (num > 0) {

cout << "number is positive." << endl;

else {

cout << "number is non-positive." <<


endl;

return 0;

}
Output
number is positive.

3. if-else if Ladder in C++


The if-else-if statements allow us to include additional situations after
the preliminary if condition. The ‘else if’ condition is checked only if
the above condition is not true. , and the `else` is the statement that
will be executed if none of the above conditions is true. If some
condition is true, then no only the associated block is executed.
Syntax if-else-if Ladder
if (condition1) {
// code to be executed if condition1 is true
}
else if (condition2) {
// code to be executed if condition2 is true
}
else {
// code to be executed if both the condition is false
}
We can use multiple else if statements with an if-else pair to specify
different conditions.
Flowchart of if-else
else-if Ladder in C++

flow diagram of the if-else-if ladder

Example of if-else-ladder
ladder in C++
The below example demonstrates the use of an if-else else-if ladder. In
the program, you are given an age and if the age is less the 13 print
child, if the age is between 13 to 18 print the growing stage, else
print adult.
 C++

// C++ program to find if the person is child,


growing age

// or adult using if else


else-if ladder
#include <iostream>

using namespace std;

int main()

int age = 18;

// if this condition is true child is


printed

if (age < 13) {

cout << "child" << endl;

// if above above if statement is not true


then we check

// this else if condition if it evalutes to


true print

// growing age

else if (age >= 1 and age <= 18) {

cout << "Growing stage" << endl;


}

// if none of above condition is true print


adult

else {

cout << "adult" << endl;

return 0;

Output
Growing stage

4. Nested if-else in C++


The Nested if-else statement contains an ‘if’ statement inside
another ‘if’ statement. This structure lets in more complex selection-
making by way of comparing multiple conditions. In this type of
statement, multiple conditions are checked, and then the body of the
last if statement is executed.
Syntax of Nested if-else in C++
if (condition1) {
// code to be executed if condition 1 is true
if (condition2) {
// code to be executed when condition 2 is true.
}
else {
// code to be executed if condition1 is true but
condition2 is false.
}
}
else {
// code to be executed when condition 1 is false
}
Flowchart of Nested if-else
Flow diagram of Nested if-else

Example of Nested if-else in C++


The below example demonstrates the use of nested if-else. In the
below program, we are given a number and we have to check
whether the number is positive or negative or zero if the number is
positive check whether it is even or odd.
 C++

// C++ program to check if the given number is


positive,

// negative or zero if positive then check if it


is even or

// odd

#include <iostream>

using namespace std;

int main()

int number = 44;

// to check if number is positive

if (number > 0) {
// to check if the positive number is
even or odd

if (number % 2 == 0) {

cout << "positive and even number"


<< endl;

else {

cout << "positive and odd number" <<


endl;

// to check if the number is 0

else if (number == 0) {

cout << "the number is zero" << endl;

// to check if the number is negative

else {

cout << "the number is negative" <<


endl;
}

return 0;

Output
positive and even number

5. Switch Statement in C++


In C++, the switch statement is used when multiple situations need
to be evaluated primarily based on the value of a variable or an
expression. switch statement acts as an alternative to multiple if
statements or if-else ladder and has a cleaner structure and it is
easy for handling multiple conditions.
Syntax of C++ switch
switch (expression) {
case value1:
// code to be executed if the value of expression
is value1.
break;
case value2:
// code to be executed if the value of expression
is value2.
break;
//…..
default:
// code to be executed if expression doesn't match
any case.
}
Flowchart of switch in C++

Flowchart of switch in C++


Example pf switch in C++
The below example demonstrates the use of switches in decision-
making. In the below program, we are given a character and you
have to give output as per the given condition: if the given input is A
then print GFG, and if the given input is B print GeeksforGeeks else
print invalid input.
 C++

// C++ program to use switch case and print


certain output

// based on some conditions

#include <iostream>

using namespace std;

int main()

char input = 'B';

switch (input) {

// if the input character is A then print


GFG

case 'A':
cout << "GFG" << endl;

break;

// if the input character is B then print


GeeksforGeeks

case 'B':

cout << "GeeksforGeeks" << endl;

break;

default:

// if th einput character is invalid


then print

// invalid input

cout << "invalid input" << endl;

return 0;

Output
GeeksforGeeks

6. Ternary Operator ( ? : ) in C++


The conditional operator is also known as a ternary operator. It is
used to write conditional operations provided by C++. The ‘?’
operator first checks the given condition, if the condition is true then
the first expression is executed otherwise the second expression is
executed. It is an alternative to an if-else condition in C++.
Syntax of Ternary Operator in C++
condition ? expression1 : expression2
Flowchart of Conditional Operator in C++

Flow Diagram of Conditional operator


Example of Ternary Operator in C++
The below program demonstrates the use of a conditional operator
to find the maximum of two numbers.
 C++

// C++ program to demonstrate the use of


ternary/conditional

// operator to find the max from two numbers

#include <iostream>

using namespace std;

int main()

int num1 = 10, num2 = 40;

int max;

// if the condition is true then num1 will


be printed

// else num2 will printed

max = (num1 > num2) ? num1 : num2;

cout << max;


return 0;

Output
40

7. Jump Statements in C++


Jump statements are used to alter the normal flow of the code. If you
want to break the flow of the program without any conditions then
these jump statements are used. C++ provides four types of jump
statements.
 break
 continue
 goto
 return
A) break
break is a control flow statement that is used to terminate the loop
and switch statements whenever a break statement is encountered
and transfer the control to the statement just after the loop.
Syntax
break;
break statement is generally used when the actual number of
iterations are not predefined so we want to terminate the loop based
on some conditions.
Flowchart of break
Flow diagram of break
Example
The below example demonstrates the use of breaks to manage the
control flow.
 C++

// C++ program to use break statement to break


the loop when

// i become 3

#include <iostream>

using namespace std;

int main()

for (int i = 0; i < 5; i++) {

// if i become 3 then break the loop and


move to

// next statement out of loop

if (i == 3) {

break;

}
cout << i << endl;

// next statements

return 0;

Output
0
1
2

B) continue
The continue statement is used to skip the loop body for the current
iteration and continue from the next iteration. Unlike the break
statement which terminates the loop completely, continue allows us
just to skip one iteration and continue with the next iteration.
Syntax
continue;
Flowchart of continue
Flow diagram of continue

Example
The below example demonstrates the use of continue to manage the
control flow.
 C++

// C++ program to use continue statement to


continue the

// loop when i become 3


#include <iostream>

using namespace std;

int main()

for (int i = 0; i < 5; i++) {

// if i become 3 then skip the rest body


of loop and

// move next iteration

if (i == 3) {

continue;

cout << i << endl;

return 0;

Output
0
1
2
4

C) goto
It is a jump statement that is used to transfer the control to another
part of the program. It transfers the control unconditionally to the
labeled statement.
Syntax
goto label;
// ...
label:
// Statement or block of code
Flowchart of goto
Flow Diagram of goto

Example
The below example demonstrates the use of the goto statement.
 C++

// C++ program to demonstrate the use of goto


statement

#include <iostream>

using namespace std;

int main()

int age = 17;

if (age < 18) {

goto Noteligible;

else {

cout << "You can vote!";

Noteligible:

cout << "You are not eligible to vote!\n";


return 0;

Output
You are not eligible to vote!

Note Use of goto is generally avoided in modern programming


practices because it may disturb the readability of the code and
make the code error-prone, although it is still valid and used
occasionally.
D) return
The return statement is used to exit the function immediately and
optionally returns a value to the calling function. It returns to the
function from where it was called and if it is the ‘main’ function then it
marks the end of the execution. So basically, return is a mechanism
used to communicate the results back to the calling function.
Syntax
return expression;
Flowchart of return
Flow diagram of return

Example
The below example demonstrates the use of a return statement to
return a value from a function.
 C++

// C++ program to use return statement to return


the sum

// calculated by a function

#include <iostream>

using namespace std;

// Function to add two numbers and returns the


result

int add(int a, int b)

int sum = a + b;

return sum; // Return the sum to the calling


code

}
int main()

int res = add(3, 5);

cout << "The sum is: " << res << endl;

return 0;

Output
The sum is: 8

Conclusion
Decision-making is an essential factor of programming in C++,
presenting flexibility and management over program execution.
When used correctly, it enhances application performance and
adaptability. However, overuse or mismanagement of decision-
making statements can lead to code complexity, decreased clarity,
and protection challenges. Striking a balance and using those
statements properly is essential to enhance your code.

Loops in c++;
In computer programming, loops are used to repeat a block of code.

For example, let's say we want to show a message 100 times. Then
instead of writing the print statement 100 times, we can use a loop.

That was just a simple example; we can achieve much more efficiency
and sophistication in our programs by making effective use of loops.

There are 3 types of loops in C++.

 for loop
 while loop
 do...while loop
This tutorial focuses on C++ for loop. We will learn about the other
type of loops in the upcoming tutorials.

C++ for loop


The syntax of for-loop is:

for (initialization; condition; update) {


// body of-loop
}

Here,

 initialization - initializes variables and is executed only once


 condition - if true , the body of for loop is executed
if false , the for loop is terminated
 update - updates the value of initialized variables and again checks the
condition
To learn more about conditions , check out our tutorial on C++
Relational and Logical Operators.
Flowchart of for Loop in C++

Flowchart of for loop in C++

Example 1: Printing Numbers From 1 to 5


#include <iostream>
using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << i << " ";
}
return 0;
}
Run Code

Output

1 2 3 4 5

Here is how this program works

Iteration Variable i Action

1st i = 1 true 1 is printed. i is increased to 2 .

2nd i = 2 true 2 is printed. i is increased to 3 .

3rd i = 3 true 3 is printed. i is increased to 4 .

4th i = 4 true 4 is printed. i is increased to 5 .

5th i = 5 true 5 is printed. i is increased to 6 .

6th i = 6 false The loop is terminated


Example 2: Display a text 5 times
// C++ Program to display a text 5 times

#include <iostream>

using namespace std;

int main() {
for (int i = 1; i <= 5; ++i) {
cout << "Hello World! " << endl;
}
return 0;
}
Run Code

Output

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Here is how this program works

Iteration Variable i Action

Hello World! is printed and i is increased to


1st i = 1 true
2.
Hello World! is printed and i is increased to
2nd i = 2 true
3.

Hello World! is printed and i is increased to


3rd i = 3 true
4.

Hello World! is printed and i is increased to


4th i = 4 true
5.

Hello World! is printed and i is increased to


5th i = 5 true
6.

6th i = 6 false The loop is terminated

Example 3: Find the sum of first n Natural


Numbers
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers

#include <iostream>

using namespace std;

int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;

for (int i = 1; i <= num; ++i) {


sum += i;
}

cout << "Sum = " << sum << endl;

return 0;
}
Run Code

Output

Enter a positive integer: 10


Sum = 55

In the above example, we have two variables num and sum .

The sum variable is assigned with 0 and the num variable is assigned
with the value provided by the user.
Note that we have used a for loop.

for(int i = 1; i <= num; ++i)

Here,

 int i = 1 : initializes the i variable


 i <= num : runs the loop as long as i is less than or equal to num

 ++i : increases the i variable by 1 in each iteration


When i becomes 11 , the condition is false and sum will be equal to 0 +

1 + 2 + ... + 10 .
Ranged Based for Loop
In C++11, a new range-based for loop was introduced to work with
collections such as arrays and vectors. Its syntax is:

for (variable : collection) {


// body of loop
}

Here, for every value in the collection , the for loop is executed and the
value is assigned to the variable .

Example 4: Range Based for Loop


#include <iostream>

using namespace std;

int main() {

int num_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for (int n : num_array) {


cout << n << " ";
}

return 0;
}
Run Code
Output

1 2 3 4 5 6 7 8 9 10

In the above program, we have declared and initialized an int array


named num_array . It has 10 items.
Here, we have used a range-based for loop to access all the items in
the array.

C++ Infinite for loop


If the condition in a for loop is always true , it runs forever (until
memory is full). For example,

// infinite for loop


for(int i = 1; i > 0; i++) {
// block of code
}

In the above program, the condition is always true which will then run
the code for infinite times.

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);

The example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:

Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);

Sr.No Loop Type & Description

while loop
1 Repeats a statement or group of statements while a given condition is true. It tests the condition
before executing the loop body.

for loop
2 Execute a sequence of statements multiple times and abbreviates the code that manages the loop
variable.

do...while loop
3
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.

nested loops
4
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
C++ Functions
A function is a block of code that performs a specific task.

Suppose we need to create a program to create a circle and color it.


We can create two functions to solve this problem:

 a function to draw the circle

 a function to color the circle

Dividing a complex problem into smaller chunks makes our program


easy to understand and reusable.

There are two types of function:

1. Standard Library Functions: Predefined in C++


2. User-defined Function: Created by users
In this tutorial, we will focus mostly on user-defined functions.

C++ User-defined Function


C++ allows the 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 the program, it all
executes the codes defined in the body of the function.

C++ Function Declaration


The syntax to declare a function is:

returnType functionName (parameter1, parameter2,...) {


// function body
}

Here's an example of a function declaration.

// function declaration
void greet() {
cout << "Hello World";
}

Here,

 the name of the function is greet()

 the return type of the function is void

 the empty parentheses mean it doesn't have any parameters

 the function body is written inside {}


Note: We will learn about returnType and parameters later in this tutorial.

Calling a Function
In the above program, we have declared a function named greet() . To
use the greet() function, we need to call it.
Here's how we can call the above greet() function.

int main() {

// calling a function
greet();

How Function works in


C++
Example 1: Display a Text
#include <iostream>
using namespace std;

// declaring a function
void greet() {
cout << "Hello there!";
}

int main() {

// calling the function


greet();

return 0;
}
Run Code

Output

Hello there!

Function Parameters
As mentioned above, a function can be declared with parameters
(arguments). A parameter is a value that is passed when declaring a
function.
For example, let us consider the function below:

void printNum(int num) {


cout << num;
}

Here, the int variable num is the function parameter.


We pass a value to the function parameter while calling the function.

int main() {
int n = 7;

// calling the function


// n is passed to the function as argument
printNum(n);

return 0;
}

Example 2: Function with Parameters


// program to print a text

#include <iostream>
using namespace std;

// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}

int main() {

int num1 = 5;
double num2 = 5.5;
;

// calling the function


displayNum(num1, num2);

return 0;
}
Run Code

Output

The int number is 5


The double number is 5.5

In the above program, we have used a function that


that has
one int parameter and one double parameter.
We then pass num1 and num2 as arguments. These values are stored by
the function parameters n1 and n2 respectively.

C++ function
with parameters
Note: The type of the arguments passed while calling the function
must match with the corresponding parameters defined in the function
declaration.

Return Statement
In the above programs, we have used void in the function declaration.
For example,

void displayNumber() {
// code
}

This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to
specify the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a
function.
For example,

int add (int a, int b) {


return (a + b);
}
Here, we have the data type int instead of void . This means that the
function returns an int value.
The code return (a + b); returns the sum of the two parameters as the
function value.
The return statement denotes that the function has ended. Any code
after return inside the function is not executed.

Example 3: Add Two Numbers


// program to add two numbers using a function

#include <iostream>

using namespace std;

// declaring a function
int add(int a, int b) {
return (a + b);
}

int main() {

int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;
}
Run Code

Output

100 + 78 = 178

In the above program, the add() function is used to find the sum of two
numbers.
We pass two int literals 100 and 78 while calling the function.
We store the returned value of the function in the variable sum , and
then we print it.

Working of
C++ Function with return statement

Notice that sum is a variable of int type. This is because the return
value of add() is of int type.
Function Prototype
In C++, the code of function declaration should be before the function
call. However, if we want to define a function after the function call, we
need to use the function prototype. For example,

// function prototype
void add(int, int);

int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}

// function definition
void add(int a, int b) {
cout << (a + b);
}

In the above code, the function prototype is:

void add(int, int);

This provides the compiler with information about the function name
and its parameters. That's why we can use the code to call a function
before the function has been defined.

The syntax of a function prototype is:

returnType functionName(dataType1, dataType2, ...);


Example 4: C++ Function Prototype
// using function definition after main() function
// function prototype is declared before main()

#include <iostream>

using namespace std;

// function prototype
int add(int, int);

int main() {
int sum;

// calling the function and storing


// the returned value in sum
sum = add(100, 78);

cout << "100 + 78 = " << sum << endl;

return 0;
}

// function definition
int add(int a, int b) {
return (a + b);
}
Run Code

Output

100 + 78 = 178
The above program is nearly identical to Example 3. The only
difference is that here, the function is defined after the function call.
That's why we have used a function prototype in this example.

Benefits of Using User-Defined Functions


 Functions make the code reusable. We can declare them once and
use them multiple times.

 Functions make the program easier as each small task is divided into
a function.

 Functions increase readability.

C++ Library Functions


Library functions are the built-in functions in C++ programming.

Programmers can use library functions by invoking the functions


directly; they don't need to write the functions themselves.

Some common library functions in C++ are sqrt(), abs(), isdigit(), etc.
In order to use library functions, we usually need to include the header
file in which these library functions are defined.

For instance, in order to use mathematical functions such


as sqrt() and abs() , we need to include the header file cmath.

Example 5: C++ Program to Find the Square


Root of a Number
#include <iostream>
#include <cmath>
using namespace std;

int main() {
double number, squareRoot;

number = 25.0;

// sqrt() is a library function to calculate the square root


squareRoot = sqrt(number);

cout << "Square root of " << number << " = " << squareRoot;

return 0;
}
Run Code

Output

Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the
square root of a number.
The function declaration of sqrt() is defined in the cmath header file.
That's why we need to use the code #include <cmath> to use
the sqrt() function.

C++ provides inline functions to reduce the function call overhead.


An inline function is a function that is expanded in line when it is
called. When the inline function is called whole code of the inline
function gets inserted or substituted at the point of the inline function
call. This substitution is performed by the C++ compiler at compile
time. An inline function may increase efficiency if it is small.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
Remember, inlining is only a request to the compiler, not a
command. The compiler can ignore the request for inlining.
The compiler may not perform inlining in such circumstances
as:
1. If a function contains a loop. (for, while and do-while)
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return
statement doesn’t exist in a function body.
5. If a function contains a switch or goto statement.

Why Inline Functions are Used?

When the program executes the function call instruction the CPU
stores the memory address of the instruction following the function
call, copies the arguments of the function on the stack, and finally
transfers control to the specified function. The CPU then executes
the function code, stores the function return value in a predefined
memory location/register, and returns control to the calling function.
This can become overhead if the execution time of the function is
less than the switching time from the caller function to called function
(callee).
For functions that are large and/or perform complex tasks, the
overhead of the function call is usually insignificant compared to the
amount of time the function takes to run. However, for small,
commonly-used functions, the time needed to make the function call
is often a lot more than the time needed to actually execute the
function’s code. This overhead occurs for small functions because
the execution time of a small function is less than the switching time.

Inline functions Advantages:


1. Function call overhead doesn’t occur.
2. It also saves the overhead of push/pop variables on the stack
when a function is called.
3. It also saves the overhead of a return call from a function.
4. When you inline a function, you may enable the compiler to
perform context-specific optimization on the body of the function.
Such optimizations are not possible for normal function calls.
Other optimizations can be obtained by considering the flows of
the calling context and the called context.
5. An inline function may be useful (if it is small) for embedded
systems because inline can yield less code than the function
called preamble and return.
Inline function Disadvantages:
1. The added variables from the inlined function consume additional
registers, After the in-lining function if the variable number which
is going to use the register increases then they may create
overhead on register variable resource utilization. This means
that when the inline function body is substituted at the point of the
function call, the total number of variables used by the function
also gets inserted. So the number of registers going to be used
for the variables will also get increased. So if after function
inlining variable numbers increase drastically then it would surely
cause overhead on register utilization.
2. If you use too many inline functions then the size of the binary
executable file will be large, because of the duplication of the
same code.
3. Too much inlining can also reduce your instruction cache hit rate,
thus reducing the speed of instruction fetch from that of cache
memory to that of primary memory.
4. The inline function may increase compile time overhead if
someone changes the code inside the inline function then all the
calling location has to be recompiled because the compiler would
be required to replace all the code once again to reflect the
changes, otherwise it will continue with old functionality.
5. Inline functions may not be useful for many embedded systems.
Because in embedded systems code size is more important than
speed.
6. Inline functions might cause thrashing because inlining might
increase the size of the binary executable file. Thrashing in
memory causes the performance of the computer to degrade. The
following program demonstrates the use of the inline function.
Example:
 C++
#include <iostream>

using namespace std;

inline int cube(int s) { return s * s * s; }

int main()

cout << "The cube of 3 is: " << cube(3) <<


"\n";

return 0;

Output
The cube of 3 is: 27

Inline function and classes


It is also possible to define the inline function inside the class. In
fact, all the functions defined inside the class are implicitly inline.
Thus, all the restrictions of inline functions are also applied here. If
you need to explicitly declare an inline function in the class then just
declare the function inside the class and define it outside the class
using the inline keyword.
Syntax:
class S
{
public:
inline int square(int s) // redundant use of inline
{
// this function is automatically inline
// function body
}
};

The above style is considered a bad programming style. The best


programming style is to just write the prototype of the function inside
the class and specify it as an inline in the function definition.
For Example:
class S
{
public:
int square(int s); // declare the function
};

inline int S::square(int s) // use inline prefix


{
}

Example:
 C++

// C++ Program to demonstrate inline functions


and classes

#include <iostream>

using namespace std;


class operation {

int a, b, add, sub, mul;

float div;

public:

void get();

void sum();

void difference();

void product();

void division();

};

inline void operation ::get()

cout << "Enter first value:";

cin >> a;

cout << "Enter second value:";

cin >> b;
}

inline void operation ::sum()

add = a + b;

cout << "Addition of two numbers: " << a + b


<< "\n";

inline void operation ::difference()

sub = a - b;

cout << "Difference of two numbers: " << a -


b << "\n";

inline void operation ::product()

mul = a * b;
cout << "Product of two numbers: " << a * b
<< "\n";

inline void operation ::division()

div = a / b;

cout << "Division of two numbers: " << a / b


<< "\n";

int main()

cout << "Program using inline function\n";

operation s;

s.get();

s.sum();

s.difference();

s.product();
s.division();

return 0;

Output:
Enter first value: 45
Enter second value: 15
Addition of two numbers: 60
Difference of two numbers: 30
Product of two numbers: 675
Division of two numbers: 3

What is wrong with the macro?


Readers familiar with the C language know that the C language uses
macro. The preprocessor replaces all macro calls directly within the
macro code. It is recommended to always use the inline function
instead of the macro. According to Dr. Bjarne Stroustrup, the creator
of C++ macros are almost never necessary in C++ and they are
error-prone. There are some problems with the use of macros in
C++. Macro cannot access private members of the class. Macros
look like function calls but they are actually not.
Example:
 C++

// C++ Program to demonstrate working of macro

#include <iostream>

using namespace std;


class S {

int m;

public:

// error

#define MAC(S::m)

};

Output:
Error: "::" may not appear in macro parameter list
#define MAC(S::m)

C++ compiler checks the argument types of inline functions and


necessary conversions are performed correctly. The preprocessor
macro is not capable of doing this. One other thing is that the
macros are managed by the preprocessor and inline functions are
managed by the C++ compiler. Remember: It is true that all the
functions defined inside the class are implicitly inline and the C++
compiler will perform inline calls of these functions, but the C++
compiler cannot perform inline if the function is virtual. The reason is
called to a virtual function is resolved at runtime instead of compile-
time. Virtual means waiting until runtime and inline means during
compilation, if the compiler doesn’t know which function will be
called, how it can perform inlining? One other thing to remember is
that it is only useful to make the function inline if the time spent
during a function call is more compared to the function body
execution time.
An example where the inline function has no effect at all:
inline void show()
{
cout << "value of S = " << S << endl;
}

The above function relatively takes a long time to execute. In


general, a function that performs an input-output (I/O) operation
shouldn’t be defined as inline because it spends a considerable
amount of time. Technically inlining of the show() function is of
limited value because the amount of time the I/O statement will take
far exceeds the overhead of a function call. Depending upon the
compiler you are using the compiler may show you a warning if the
function is not expanded inline.
Programming languages like Java & C# don’t support inline
functions. But in Java, the compiler can perform inlining when the
small final method is called because final methods can’t be
overridden by subclasses, and the call to a final method is resolved
at compile time.
In C# JIT compiler can also optimize code by inlining small function
calls (like replacing the body of a small function when it is called in a
loop). The last thing to keep in mind is that inline functions are a
valuable feature of C++. Appropriate use of inline functions can
provide performance enhancement but if inline functions are used
arbitrarily then they can’t provide better results. In other words, don’t
expect a better performance of the program. Don’t make every
function inline. It is better to keep inline functions as small as
possible.

Function overloading in C++;

Function overloading is a feature of object-oriented programming


where two or more functions can have the same name but different
parameters. When a function name is overloaded with different jobs
it is called Function Overloading. In Function Overloading “Function”
name should be the same and the arguments should be different.
Function overloading can be considered as an example of
a polymorphism feature in C++.
If multiple functions having same name but parameters of the
functions should be different is known as Function Overloading.
If we have to perform only one operation and having same name of
the functions increases the readability of the program.
Suppose you have to perform addition of the given numbers but
there can be any number of arguments, if you write the function such
as a(int,int) for two parameters, and b(int,int,int) for three parameters
then it may be difficult for you to understand the behavior of the
function because its name differs.

The parameters should follow any one or more than one of the
following conditions for Function overloading:
 Parameters should have a different type
add(int a, int b)
add(double a, double b)
Below is the implementation of the above discussion:
C++

#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}

// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);

return 0;
}

Output
sum = 12
sum = 11.5

 Parameters should have a different number


add(int a, int b)
add(int a, int b, int c)
Below is the implementation of the above discussion:
C++

#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(int a, int b, int c)


{
cout << endl << "sum = " << (a + b + c);
}

// Driver code
int main()
{
add(10, 2);
add(5, 6, 4);

return 0;
}

Output
sum = 12
sum = 15

 Parameters should have a different sequence of parameters.


add(int a, double b)
add(double a, int b)
Below is the implementation of the above discussion:
C++

#include<iostream>
using namespace std;

void add(int a, double b)


{
cout<<"sum = "<<(a+b);
}

void add(double a, int b)


{
cout<<endl<<"sum = "<<(a+b);
}

// Driver code
int main()
{
add(10,2.5);
add(5.5,6);

return 0;
}

Output
sum = 12.5
sum = 11.5

Following is a simple C++ example to demonstrate function


overloading.
CPP

#include <iostream>
using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}

int main() {
print(10);
print(10.10);
print("ten");
return 0;
}

Output
Here is int 10
Here is float 10.1
Here is char* ten
C++

#include<iostream>
using namespace std;

void add(int a, int b)


{
cout<<"sum ="<<(a+b);
}

void add(int a, int b,int c)


{
cout<<endl<<"sum ="<<(a+b+c);
}

main()
{

add(10,2);
add(5,6,4);
return 0;
}
C++
#include<iostream>
using namespace std;

void add(int a, double b)


{
cout<<"sum ="<<(a+b);
}
void add(double a, int b)
{
cout<<endl<<"sum ="<<(a+b);
}

main()
{
add(10,2.5);
add(5.5,6);
return 0;
}
How does Function Overloading work?
 Exact match:- (Function name and Parameter)
 If a not exact match is found:–
->Char, Unsigned char, and short are promoted to an int.
->Float is promoted to double
 If no match is found:
->C++ tries to find a match through the standard
conversion.
 ELSE ERROR
Note: In C++, function overloading is primarily based on the function
name and the types or number of its parameters. The return type
alone does not distinguish overloaded functions. Therefore,
changing only the return type of a function without changing its
parameters does not create an overload and may lead to a
compilation error due to ambiguity.

You might also like