0% found this document useful (0 votes)
7 views

C++ Unit I-1

The document discusses object oriented programming in C++. It defines key concepts like classes, objects, inheritance, abstraction, encapsulation and polymorphism. It also discusses C++ tokens including keywords, identifiers, constants and operators.

Uploaded by

abthulrasik211
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)
7 views

C++ Unit I-1

The document discusses object oriented programming in C++. It defines key concepts like classes, objects, inheritance, abstraction, encapsulation and polymorphism. It also discusses C++ tokens including keywords, identifiers, constants and operators.

Uploaded by

abthulrasik211
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/ 81

I YEAR – II SEMESTER

COURSE CODE: 7BCE2C1

CORE COURSE-III–OBJECT ORIENTED PROGRAMMING WITH C++

Unit I
Software Crisis – Software Evolution – Basic Concepts of Object-Oriented
Programming – Benefits of OOP – Object-Oriented Languages - Applications of
OOP – Application of C++ - Structure of a C++ Program – Tokens – Keywords –
Identifiers – Basic Data Types – Userdefined Data types – Derived data types –
Symbolic constants – Type compatibility – Declaration of variables – Dynamic
initialization of variables –Reference variables – Operators in C++ - Manipulators
– Type cast operator – Expressions and their types-Implicit conversions – Control
structures – The main function – Function prototyping – inline functions –
Function overloading.

Software Crisis:
Software Crisis is a term used in computer science for the difficulty of writing
useful and efficient computer programs in the required time .software crisis was
due to using same workforce, same methods, same tools even though rapidly
increasing in software demand, complexity of software and software challenges.
With increase in the complexity of software, many software problems arise
because existing methods were insufficient.
Causes of Software Crisis:
• The cost of owning and maintaining software was as expensive as developing
the software
• At that time Projects was running over-time
• At that time Software was very inefficient
• The quality of software was low quality

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 1
• Software often did not meet requirements
• The average software project overshoots its schedule by half
• At that time Software was never delivered
Solution of Software Crisis:
There is no single solution to the crisis.one possible solution of software crisis
is Software Engineering because software engineering is a systematic, disciplined
and quantifiable approach. For preventing software crisis, there are some
guidelines:
• Reduction in software over-budget
• The quality of software must be high
• Less time needed for software project
• Experience working team member on software project
• Software must be delivered

Introduction to C++
C++, as we all know is an extension to C language and was developed by Bjarne stroustrup at
bell labs. C++ is an intermediate level language, as it comprises a confirmation of both high level
and low level language features. C++ is a statically typed, free form, multiparadigm, compiled
general-purpose language.

C++ is an Object Oriented Programming language but is not purely Object Oriented. Its
features like Friend and Virtual, violate some of the very important OOPS features, rendering
this language unworthy of being called completely Object Oriented. Its a middle level language.

Benefits of C++ over C Language


The major difference being OOPS concept, C++ is an object oriented language whereas C
language is a procedural language. Apart form this there are many other features of C++ which
gives this language an upper hand on C laguage.

Following features of C++ makes it a stronger language than C,

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 2
1. There is Stronger Type Checking in C++.
2. All the OOPS features in C++ like Abstraction, Encapsulation, Inheritance etc makes it
more worthy and useful for programmers.
3. C++ supports and allows user defined operators (i.e Operator Overloading) and function
overloading is also supported in it.
4. Exception Handling is there in C++.
5. The Concept of Virtual functions and also Constructors and Destructors for Objects.
6. Inline Functions in C++ instead of Macros in C language. Inline functions make complete
function body act like Macro, safely.
7. Variables can be declared anywhere in the program in C++, but must be declared before
they are used.

Why Use C++

C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.

C++ is an object-oriented programming language which gives a clear structure to programs and
allows code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.

C++ is fun and easy to learn!

As C++ is close to C# and Java, it makes it easy for programmers to switch to C++ or vice versa

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 3
Object Oriented Programming in C++
Object Oriented programming is a programming style that is associated with the concept of
Class, Objects and various other concepts revolving around these two, like Inheritance,
Polymorphism, Abstraction, Encapsulation etc.

In the video below, we have explained the basic concepts of Object Oriented Programming with
help of a very easy to understand example. If you want to skip the video, everything is covered
below as well.

Let us try to understand a little about all these, through a simple example. Human Beings are
living forms, broadly categorized into two types, Male and Female. Right? Its true. Every Human
being(Male or Female) has two legs, two hands, two eyes, one nose, one heart etc. There are
body parts that are common for Male and Female, but then there are some specific body parts,
present in a Male which are not present in a Female, and some body parts present in Female but
not in Males.

All Human Beings walk, eat, see, talk, hear etc. Now again, both Male and Female, performs
some common functions, but there are some specifics to both, which is not valid for the other.
For example : A Female can give birth, while a Male cannot, so this is only for the Female.

Human Anatomy is interesting, isn't it? But let's see how all this is related to C++ and OOPS.
Here we will try to explain all the OOPS concepts through this example and later we will have
the technical definitons for all this.

Class

Here we can take Human Being as a class. A class is a blueprint for any functional entity which
defines its properties and its functions. Like Human Being, having body parts, and performing
various actions.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 4
Inheritance

Considering HumanBeing a class, which has properties like hands, legs, eyes etc, and functions
like walk, talk, eat, see etc. Male and Female are also classes, but most of the properties and
functions are included in HumanBeing, hence they can inherit everything from
class HumanBeing using the concept of Inheritance.

Objects

My name is Abhishek, and I am an instance/object of class Male. When we say, Human Being,
Male or Female, we just mean a kind, you, your friend, me we are the forms of these classes. We
have a physical existence while a class is just a logical definition. We are the objects.

Abstraction

Abstraction means, showcasing only the required things to the outside world while hiding the
details. Continuing our example, Human Being's can talk, walk, hear, eat, but the details are
hidden from the outside world. We can take our skin as the Abstraction factor in our case, hiding
the inside mechanism.

Encapsulation

This concept is a little tricky to explain with our example. Our Legs are binded to help us walk.
Our hands, help us hold things. This binding of the properties to functions is called
Encapsulation.

Polymorphism

Polymorphism is a concept, which allows us to redefine the way something works, by either
changing how it is done or by changing the parts using which it is done. Both the ways have
different terms for them.

If we walk using our hands, and not legs, here we will change the parts used to perform
something. Hence this is called Overloading.

And if there is a defined way of walking, but I wish to walk differently, but using my legs, like
everyone else. Then I can walk like I want, this will be called as Overriding.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 5
*****

C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Keywords: Keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can’t be used as variable names because by doing so, we are trying
to assign a new meaning to the keyword which is not allowed. You cannot redefine keywords.
However, you can specify the text to be substituted for keywords before compilation by using
C/C++ preprocessor directives. C language supports 32 keywords which are given below:

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 6
While in C++ there are 31 additional keywords other than C Keywords they are:

asm bool catch class

const_cast delete dynamic_cast explicit

export false friend inline

mutable namespace new operator

private protected public reinterpret_cast

static_cast template this throw

true try typeid typename

using virtual wchar_t

1. Identifiers: Identifiers are used as the general terminology for the naming of variables,
functions and arrays. These are user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the underscore(_) as a first character.
Identifier names must differ in spelling and case from any keywords. You cannot use
keywords as identifiers; they are reserved for special use. Once declared, you can use the
identifier in later program statements to refer to the associated value. A special kind of
identifier, called a statement label, can be used in goto statements.

There are certain rules that should be followed while naming c identifiers:
• They must begin with a letter or underscore(_).
• They must consist of only letters, digits, or underscore. No other special character is
allowed.
• It should not be a keyword.
• It must not contain white space.
• It should be up to 31 characters long as only the first 31 characters are significant.
• main: method name.
• a: variable name.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 7
2. Constants: Constants are also like normal variables. But, the only difference is, their
values can not be modified by the program once they are defined. Constants refer to fixed
values. They are also called literals.
Constants may belong to any of the data type.
3. Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
1. Integer constants – Example: 0, 1, 1218, 12482
2. Real or Floating-point constants – Example: 0.0, 1203.03, 30486.184
3. Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal:
(013)16 = (19)10
4. Character constants -Example: ‘a’, ‘A’, ‘z’
5. String constants -Example: “GeeksforGeeks”
4. Strings: Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in double-
quotes. Whereas, a character is enclosed in single quotes in C and C++.Declarations for
String:
• char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
• char string[20] = “geeksforgeeks”;
• char string [] = “geeksforgeeks”;
• when we declare char as “string[20]”, 20 bytes of memory space is allocated for
holding the string value.
• When we declare char as “string[]”, memory space will be allocated as per the
requirement during the execution of the program.
5. Special Symbols: The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #
• Brackets[]: Opening and closing brackets are used as array element reference. These
indicate single and multidimensional subscripts.
• Parentheses(): These special symbols are used to indicate function calls and function
parameters.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 8
• Braces{}: These opening and ending curly braces mark the start and end of a block of
code containing more than one executable statement.
• Comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
• Colon(:): It is an operator that essentially invokes something called an initialization
list.
• Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That’s why each individual statement must be ended with a semicolon.
• Asterisk (*): It is used to create a pointer variable.
• Assignment operator(=): It is used to assign values.
• Pre-processor (#): The preprocessor is a macro processor that is used automatically by
the compiler to transform your program before actual compilation.
6. Operators: Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:
• Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators.For Example increment and decrement operators
• Binary Operators: Those operators that require two operands to act upon are called
binary operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
*****

C++ Data Types


All variables use data-type during declaration to restrict the type of data to be stored. Therefore,
we can say that data types are used to tell the variables the type of data it can store. Whenever a

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 9
variable is defined in C++, the compiler allocates some memory for that variable based on the
data-type with which it is declared. Every data type requires a different amount of memory.

Data types in C++ is mainly divided into three types:

1. Primitive data types:


These data types are built-in or predefined data types and can be used directly by the user to
declare variables. example: int, char , float, bool etc. Primitive data types available in C++
are:
• Integer
• Character
• Boolean
• Floating Point
• Double Floating Point
• Valueless or Void
• Wide Character

Primitive data types available in C++.

• Integer: Keyword used for integer data types is int. Integers typically requires 4 bytes of
memory space and ranges from -2147483648 to 2147483647.

• Character: Character data type is used for storing characters. Keyword used for character
data type is char. Characters typically requires 1 byte of memory space and ranges from -
128 to 127 or 0 to 255.

• Boolean: Boolean data type is used for storing boolean or logical values. A boolean
variable can store either true or false. Keyword used for boolean data type is bool.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 10
• Floating Point: Floating Point data type is used for storing single precision floating point
values or decimal values. Keyword used for floating point data type is float. Float variables
typically requires 4 byte of memory space.

• Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating point
data type is double. Double variables typically requires 8 byte of memory space.

• void: Void means without any value. void datatype represents a valueless entity. Void data
type is used for those function which does not returns a value.

• Wide Character: Wide character data type is also a character data type but this data type
has size greater than the normal 8-bit datatype. Represented by wchar_t. It is generally 2
or 4 bytes long.

2. Derived data types:


The data-types that are derived from the primitive or built-in datatypes are referred to as
Derived Data Types. These can be of four types namely:
• Function
• Array
• Pointer
• Reference
Let’s briefly understand each of the following derived datatypes:

1. Function: A function is a block of code or program-segment that is defined to perform a


specific well-defined task. A function is generally defined to save the user from writing the
same lines of code again and again for the same input. All the lines of code are put together
inside a single function and this can be called anywhere required. main() is a default
function that is defined in every program of C++.
Syntax:

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 11
FunctionType FunctionName(parameters)

Example:
filter_none

edit
play_arrow
brightness_4

// C++ program to demonstrate

// Function Derived Type

#include <iostream>

using namespace std;

// max here is a function derived type

int max(int x, int y)

if (x > y)

return x;

else

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 12
return y;

// main is the default function derived type

int main()

int a = 10, b = 20;

// Calling above function to

// find max of 'a' and 'b'

int m = max(a, b);

cout << "m is " << m;

return 0;

Output:
m is 20

2. Array: An array is a collection of items stored at continuous memory locations. The idea of
array is to represent many instances in one variable.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 13
Syntax:
DataType ArrayName[size_of_array];

Example:
filter_none

edit
play_arrow
brightness_4

// C++ program to demonstrate

// Array Derived Type

#include <iostream>

using namespace std;

int main()

// Array Derived Type

int arr[5];

arr[0] = 5;

arr[2] = -10;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 14
// this is same as arr[1] = 2

arr[3 / 2] = 2;

arr[3] = arr[0];

cout<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3];

return 0;

Output:
5 2 -10 5
3. Pointers: Pointers are symbolic representation of addresses. They enable programs to
simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s
general declaration in C/C++ has the format:
Syntax:
datatype *var_name;

Example:
int *ptr;

ptr points to an address

which holds int data

Example:
filter_none

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 15
edit
play_arrow
brightness_4

// C++ program to illustrate

// Pointers Derived Type

#include <bits/stdc++.h>

using namespace std;

void geeks()

int var = 20;

// Pointers Derived Type

// declare pointer variable

int* ptr;

// note that data type of ptr

// and var must be same

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 16
ptr = &var;

// assign the address of a variable

// to a pointer

cout << "Value at ptr = "

<< ptr << "\n";

cout << "Value at var = "

<< var << "\n";

cout << "Value at *ptr = "

<< *ptr << "\n";

// Driver program

int main()

geeks();

Output:
Value at ptr = 0x7ffc10d7fd5c
Value at var = 20

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 17
Value at *ptr = 20

4. Reference: When a variable is declared as reference, it becomes an alternative name for an


existing variable. A variable can be declared as reference by putting ‘&’ in the declaration.
Example:
filter_none

edit
play_arrow
brightness_4

// C++ program to illustrate

// Reference Derived Type

#include <iostream>

using namespace std;

int main()

int x = 10;

// Reference Derived Type

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 18
// ref is a reference to x.

int& ref = x;

// Value of x is now changed to 20

ref = 20;

cout << "x = " << x << endl;

// Value of x is now changed to 30

x = 30;

cout << "ref = " << ref << endl;

return 0;

Output:
x = 20
ref = 30

3. ABSTRACT OR USER-DEFINED DATA TYPES: These data types are defined by user
itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined
datatypes:
• Class
• Structure

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 19
• Union
• Enumeration
• Typedef defined DataType

3.User-Defined DataTypes:

The data types that are defined by the user are called the derived datatype or user-defined
derived data type.
These types include:

• Class
• Structure
• Union
• Enumeration
• Typedef defined DataType
Below is the detailed description of the following types:

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 20
1. 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.
Example:
filter_none

edit
play_arrow
brightness_4

// C++ program to demonstrate

// Class

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 21
#include <bits/stdc++.h>

using namespace std;

class Geeks {

// Access specifier

public:

// Data Members

string geekname;

// Member Functions()

void printname()

cout << "Geekname is: " << geekname;

};

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 22
int main()

// Declare an object of class geeks

Geeks obj1;

// accessing data member

obj1.geekname = "GeeksForGeeks";

// accessing member function

obj1.printname();

return 0;

Output:

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 23
Geekname is: GeeksForGeeks

2. Structure: A structure is a user defined data type in C/C++. A structure creates a data type
that can be used to group items of possibly different types into a single type.
Syntax:
struct address {

char name[50];

char street[100];

char city[50];

char state[20];

int pin;

};

Example:
filter_none

edit
play_arrow
brightness_4

// C++ program to demonstrate

// Structures in C++

#include <iostream>

using namespace std;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 24
struct Point {

int x, y;

};

int main()

// Create an array of structures

struct Point arr[10];

// Access array members

arr[0].x = 10;

arr[0].y = 20;

cout << arr[0].x << ", " << arr[0].y;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 25
return 0;

Output:
10, 20

3. Union: Like Structures, union is a user defined data type. In union, all members share the
same memory location. For example in the following C program, both x and y share the
same location. If we change x, we can see the changes being reflected in y.
filter_none

edit
play_arrow
brightness_4

#include <iostream>

using namespace std;

// Declaration of union is same as the structures

union test {

int x, y;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 26
};

int main()

// A union variable t

union test t;

// t.y also gets value 2

t.x = 2;

cout << "After making x = 2:"

<< endl

<< "x = " << t.x

<< ", y = " << t.y

<< endl;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 27
// t.x is also updated to 10

t.y = 10;

cout << "After making Y = 10:"

<< endl

<< "x = " << t.x

<< ", y = " << t.y

<< endl;

return 0;

Output:
After making x = 2:

x = 2, y = 2

After making Y = 10:

x = 10, y = 10

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 28
4. Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to
assign names to integral constants, the names make a program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};

filter_none

edit
play_arrow
brightness_4

// Program to demonstrate working

// of enum in C++

#include <iostream>

using namespace std;

enum week { Mon,

Tue,

Wed,

Thur,

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 29
Fri,

Sat,

Sun };

int main()

enum week day;

day = Wed;

cout << day;

return 0;

Output:
2

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 30
5. Typedef : C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name
for an existing type. This can increase the portability(the ability of a program to be used
across different types of machines; i.e., mini, mainframe, micro, etc; without much changes
into the code)of a program as only the typedef statements would have to be changed. Using
typedef one can also aid in self-documenting code by allowing descriptive names for the
standard data types.
Syntax:
typedef type name;

where type is any C++ data type and name is the new name for this data type.
This defines another name for the standard type of C++.
Example:
filter_none

edit
play_arrow
brightness_4

// C++ program to demonstrate typedef

#include <iostream>

using namespace std;

// After this line BYTE can be used

// in place of unsigned char

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 31
typedef unsigned char BYTE;

int main()

BYTE b1, b2;

b1 = 'c';

cout << " " << b1;

return 0;

Output:
C

Declaration of Variables:

A variable provides us with named storage that our programs can manipulate. Each variable in
C++ has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++
is case-sensitive

Variable Definition in C++

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 32
A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type, and contains a list of one or more variables of that
type as follows −
type variable_list;
Here, type must be a valid C++ data type including char, w_char, int, float, double, bool or any
user-defined object, etc., and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the
compiler to create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables is
undefined.

Variable Declaration in C++

A variable declaration provides assurance to the compiler that there is one variable existing with
the given type and name so that compiler proceed for further compilation without needing
complete detail about the variable. A variable declaration has its meaning at the time of
compilation only, compiler needs actual variable definition at the time of linking of the
program.
A variable declaration is useful when you are using multiple files and you define your variable
in one of the files which will be available at the time of linking of the program. You will
use extern keyword to declare a variable at any place. Though you can declare a variable
multiple times in your C++ program, but it can be defined only once in a file, a function or a
block of code.
Example
Try the following example where a variable has been declared at the top, but it has been defined
inside the main function −
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 33
#include <iostream>
using namespace std;

// Variable declaration:
extern int a, b;
extern int c;
extern float f;

int main () {
// Variable definition:
int a, b;
int c;
float f;

// actual initialization
a = 10;
b = 20;
c = a + b;

cout << c << endl ;

f = 70.0/3.0;
cout << f << endl ;

return 0;
}

When the above code is compiled and executed, it produces the following result −
30
23.3333

Operators in C++

Previous Page

Next Page

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 34
• Arithmetic Operators

• Relational Operators

• Logical Operators

• Bitwise Operators

• Assignment Operators

• Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.

Arithmetic Operators

There are following arithmetic operators supported by C++ language −

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after B % A will give 0


an integer division

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 35
++ Increment operator, increases integer A++ will give 11
value by one

-- Decrement operator, decreases integer A-- will give 9


value by one

Relational Operators

There are following relational operators supported by C++ language

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

== Checks if the values of two operands are (A == B) is not true.


equal or not, if yes then condition
becomes true.

!= Checks if the values of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand, if
yes then condition becomes true.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 36
< Checks if the value of left operand is less (A < B) is true.
than the value of right operand, if yes then
condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand, if yes then condition becomes
true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right operand,
if yes then condition becomes true.

Logical Operators

There are following logical operators supported by C++ language.

Assume variable A holds 1 and variable B holds 0, then −

Show Examples

Operator Description Example

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of the (A || B) is true.


two operands is non-zero, then condition

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 37
becomes true.

! Called Logical NOT Operator. Use to !(A && B) is true.


reverses the logical state of its operand. If
a condition is true, then Logical NOT
operator will make false.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
are as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 38
A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then −

Show Examples

Operator Description Example

& Binary AND Operator copies a bit to the


(A & B) will give 12 which is 0000 1100
result if it exists in both operands.

| Binary OR Operator copies a bit if it exists (A | B) will give 61 which is 0011 1101
in either operand.

^ Binary XOR Operator copies the bit if it is


(A ^ B) will give 49 which is 0011 0001
set in one operand but not both.

~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100 0011 in
unary and has the effect of 'flipping' bits. 2's complement form due to a signed
binary number.

<< Binary Left Shift Operator. The left


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

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 39
>> Binary Right Shift Operator. The left
operands value is moved right by the
A >> 2 will give 15 which is 0000 1111
number of bits specified by the right
operand.

Assignment Operators

There are following assignment operators supported by C++ language −

Show Examples

Operator Description Example

= Simple assignment operator, Assigns values C = A + B will assign value of A + B


from right side operands to left side operand. into C

+= Add AND assignment operator, It adds right


operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand.

-= Subtract AND assignment operator, It


subtracts right operand from the left operand C -= A is equivalent to C = C - A
and assign the result to left operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left operand C *= A is equivalent to C = C * A
and assign the result to left operand.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 40
/= Divide AND assignment operator, It divides
left operand with the right operand and assign C /= A is equivalent to C = C / A
the result to left operand.

%= Modulus AND assignment operator, It takes


modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment


C ^= 2 is same as C = C ^ 2
operator.

|= Bitwise inclusive OR and assignment


C |= 2 is same as C = C | 2
operator.

Misc Operators

The following table lists some other operators that C++ supports.

Sr.No Operator & Description

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 41
1 sizeof

sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer,
and will return 4.

2 Condition ? X : Y

Conditional operator (?). If Condition is true then it returns value of X otherwise returns
value of Y.

3 ,

Comma operator causes a sequence of operations to be performed. The value of the entire
comma expression is the value of the last expression of the comma-separated list.

4 . (dot) and -> (arrow)

Member operators are used to reference individual members of classes, structures, and
unions.

5 Cast

Casting operators convert one data type to another. For example, int(2.2000) would return
2.

6 &

Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.

7 *

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 42
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

Operators Precedence in C++

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Show Examples

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 43
Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Scope resolution operator in C++

The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you
can still use them. The scope resolution operator can be used as both unary and binary. You can
use the unary scope operator if a namespace scope or global scope name is hidden by a particular
declaration of an equivalent name during a block or class. For example, if you have a global
variable of name my_var and a local variable of name my_var, to access global my_var, you'll
need to use the scope resolution operator.

example
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 44
#include <iostream>

using namespace std;

int my_var = 0;

int main(void) {

int my_var = 0;

::my_var = 1; // set global my_var to 1

my_var = 2; // set local my_var to 2

cout << ::my_var << ", " << my_var;

return 0;

Output

This will give the output −

1, 2

Manipulators in C++ with Examples


• Last Updated : 09 Jun, 2020

Manipulators:

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 45
Manipulators are helping functions that can modify the input/output stream. It does not mean
that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.
For example, if we want to print the hexadecimal value of 100 then we can print it as:

cout<<setbase(16)<<100

Types of Manipulators
There are various types of manipulators:

1. Manipulators without arguments: The most important manipulators defined by


the IOStream library are provided below.
• endl: It is defined in ostream. It is used to enter a new line and after entering a new line it
flushes (i.e. it forces all the output written on the screen or in the file) the output stream.
• ws: It is defined in istream and is used to ignore the whitespaces in the string sequence.
• ends: It is also defined in ostream and it inserts a null character into the output stream. It
typically works with std::ostrstream, when the associated output buffer needs to be null-
terminated to be processed as a C string.
• flush: It is also defined in ostream and it flushes the output stream, i.e. it forces all the
output written on the screen or in the file. Without flush, the output would be the same,
but may not appear in real-time.

Examples:

#include <iostream>

#include <istream>

#include <sstream>

#include <string>

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 46
using namespace std;

int main()

istringstream str(" Programmer");

string line;

// Ignore all the whitespace in string

// str before the first word.

getline(str >> std::ws, line);

// you can also write str>>ws

// After printing the output it will automatically

// write a new line in the output stream.

cout << line << endl;

// without flush, the output will be the same.

cout << "only a test" << flush;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 47
// Use of ends Manipulator

cout << "\na";

// NULL character will be added in the Output

cout << "b" << ends;

cout << "c" << endl;

return 0;

Output:
Programmer
only a test
abc

Type Cast Operator:

A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.

The most general cast supported by most of the C++ compilers is as follows −

(type) expression

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 48
Where type is the desired data type. There are other casting operators supported by C++, they
are listed below −

• const_cast<type> (expr) − The const_cast operator is used to explicitly override const


and/or volatile in a cast. The target type must be the same as the source type except for
the alteration of its const or volatile attributes. This type of casting manipulates the const
attribute of the passed object, either to be set or removed.

• dynamic_cast<type> (expr) − The dynamic_cast performs a runtime cast that verifies


the validity of the cast. If the cast cannot be made, the cast fails and the expression
evaluates to null. A dynamic_cast performs casts on polymorphic types and can cast a
A* pointer into a B* pointer only if the object being pointed to actually is a B object.

• reinterpret_cast<type> (expr) − The reinterpret_cast operator changes a pointer to any


other type of pointer. It also allows casting from pointer to an integer type and vice
versa.

• static_cast<type> (expr) − The static_cast operator performs a nonpolymorphic cast.


For example, it can be used to cast a base class pointer into a derived class pointer.

All of the above-mentioned casting operators will be used while working with classes and
objects. For now, try the following example to understand a simple cast operators available in
C++. Copy and paste the following C++ program in test.cpp file and compile and run this
program.

Live Demo

#include <iostream>
using namespace std;

main() {
double a = 21.09399;
float b = 10.20;
int c ;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 49
c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;

c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;

return 0;
}

When the above code is compiled and executed, it produces the following result −

Line 1 - Value of (int)a is :21


Line 2 - Value of (int)b is :10

Control Structures

 A program is usually not limited to a linear sequence of instructions. During its process it
may bifurcate, repeat code or take decisions. For that purpose, C++ provides control
structures that serve to specify what has to be done to perform our program.
 With the introduction of control sequences we are going to have to introduce a new
concept: the block of instructions. A block of instructions is a group of instructions
separated by semicolons (;) but grouped in a block delimited by curly bracket
signs: { and }.
 Most of the control structures that we will see in this section allow a generic statement as
a parameter, this refers to either a single instruction or a block of instructions, as we
want. If we want the statement to be a single instruction we do not need to enclose it
between curly-brackets ({}). If we want the statement to be more than a single instruction
we must enclose them between curly brackets ({}) forming a block of instructions.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 50
Conditional structure: Simple if:

 It is used to execute an instruction or block of instructions only if a condition is fulfilled.


Its form is:
 if (condition) statement
 where condition is the expression that is being evaluated. If this condition
is true, statement is executed. If it is false, statement is ignored (not executed) and the
program continues on the next instruction after the conditional structure.
 For example, the following code fragment prints out x is 100 only if the value stored in
variable x is indeed 100:
 if (x == 100)
cout << "x is 100";
 If we want more than a single instruction to be executed in case that condition is true we
can specify a block of instructions using curly brackets { }:
 if (x == 100)
{
cout << "x is ";
cout << x;
}

if else:

 We can additionally specify what we want that happens if the condition is not fulfilled by
using the keyword else. Its form used in conjunction with if is:
 if (condition) statement1 else statement2
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 51
 prints out on the screen x is 100 if indeed x is worth 100, but if it is not -and only if not- it
prints out x is not 100.

Else if or ladder if:

 The if + else structures can be concatenated with the intention of verifying a range of
values. The following example shows its use telling if the present value stored in x is
positive, negative or none of the previous, that is to say, equal to zero.
 if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

Repetitive structures or loops

 Loops have as objective to repeat a statement a certain number of times or while a


condition is fulfilled.
 The while loop.
Its format is:
 while (expression) statement
and its function is simply to repeat statement while expression is true

For example

 // custom countdown using while


 #include <iostream.h>

int main ()

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 52
{

int n;

cout << "Enter the starting number > ";

cin >> n;

while (n>0)

cout << n << ", "; --n;

cout << "FIRE!";

return 0;

Output:

 Enter the starting number > 8


8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Do while Loop:

 Format:
do statement while (condition);
 Its functionality is exactly the same as the while loop except that condition in the do-
while is evaluated after the execution of statement instead of before, granting at least one
execution of statement even if condition is never fulfilled. For example, the following
program echoes any number you enter until you enter 0.
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 53
Example:

 // number echoer
 #include <iostream.h>

int main ()

unsigned long n;

do

cout << "Enter number (0 to end): ";

cin >> n;

cout << "You entered: " << n << "\n";

} while (n != 0);

return 0;

Output:

 Enter number (0 to end): 12345


You entered: 12345
Enter number (0 to end): 160277
You entered: 160277

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 54
Enter number (0 to end): 0
You entered: 0

For Loop:

 Its format is:


 for (initialization; condition; increase)
 statement;
 and its main function is to repeat statement while condition remains true, like
the while loop. But in addition, for provides places to specify an initialization instruction
and an increase instruction. So this loop is specially designed to perform a repetitive
action with a counter.

Example:

 // countdown using a for loop


 #include <iostream.h>

int main ()

for (int n=10; n>0; n--)

cout << n << ", ";

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 55
}

cout << "FIRE!";

return 0;

Output:

 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Jump statements
The break statement

Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to
end an infinite loop, or to force it to end before its natural end. For example, we are going to stop
the count down before its natural end (maybe because of an engine check failure?):

// break loop example 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

#include <iostream>
using namespace std;

int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 56
The continue statement

The continue statement causes the program to skip the rest of the loop in the current iteration as
if the end of the statement block had been reached, causing it to jump to the start of the following
iteration. For example, we are going to skip the number 5 in our countdown:

// continue loop example 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!


#include <iostream>
using namespace std;

int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}

The goto statement


goto allows to make an absolute jump to another point in the program. You should use this
feature with caution since its execution causes an unconditional jump ignoring any type of
nesting limitations.
The destination point is identified by a label, which is then used as an argument for the goto
statement. A label is made of a valid identifier followed by a colon (:).

Generally speaking, this instruction has no concrete use in structured or object oriented
programming aside from those that low-level programming fans may find for it. For example,
here is our countdown loop using goto:

// goto loop example 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 57
#include <iostream>
using namespace std;

int main ()
{
int n=10;
loop:
cout << n << ", ";
n--;
if (n>0) goto loop;
cout << "FIRE!\n";
return 0;
}

The exit function

exit is a function defined in the cstdlib library.

The purpose of exit is to terminate the current program with a specific exit code. Its prototype is:

void exit (int exitcode);

The exitcode is used by some operating systems and may be used by calling programs. By
convention, an exit code of 0 means that the program finished normally and any other value
means that some error or unexpected results happened.

Functions in C/C++

A function is a set of statements that take inputs, do some specific computation and produces
output.

The idea is to put some commonly or repeatedly done task together and make a function so that
instead of writing the same code again and again for different inputs, we can call the function.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 58
The general form of a function is:

filter_none
brightness_4

return_type function_name([ arg1_type arg1_name, ... ]) { code }

Example:
Below is a simple C/C++ program to demonstrate functions.

• C
• C++
filter_none
edit
play_arrow
brightness_4

#include <stdio.h>

// An example function that takes two parameters 'x' and 'y'

// as input and returns max of two input numbers

int max(int x, int y)

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 59
if (x > y)

return x;

else

return y;

// main function that doesn't receive any parameter and

// returns integer.

int main(void)

int a = 10, b = 20;

// Calling above function to find max of 'a' and 'b'

int m = max(a, b);

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 60
printf("m is %d", m);

return 0;

Output:

m is 20

Why do we need functions?


• Functions help us in reducing code redundancy. If functionality is performed at multiple
places in software, then rather than writing the same code, again and again, we create a
function and call it everywhere. This also helps in maintenance as we have to change at one
place if we make future changes to the functionality.
• Functions make code modular. Consider a big file having many lines of codes. It becomes
really simple to read and use the code if the code is divided into functions.
• Functions provide abstraction. For example, we can use library functions without worrying
about their internal working.
Function Declaration
A function declaration tells the compiler about the number of parameters function takes, data-
types of parameters and return type of function. Putting parameter names in function declaration
is optional in the function declaration, but it is necessary to put them in the definition. Below are
an example of function declarations. (parameter names are not there in below declarations)
filter_none
M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 61
brightness_4

// A function that takes two integers as parameters

// and returns an integer

int max(int, int);

// A function that takes a int pointer and an int variable as parameters

// and returns an pointer of type int

int *swap(int*,int);

// A function that takes a charas parameters

// and returns an reference variable

char *call(char b);

// A function that takes a char and an int as parameters

// and returns an integer

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 62
int fun(char, int);

It is always recommended to declare a function before it is used (See this, this and this for
details)
In C, we can do both declaration and definition at the same place, like done in the above example
program.

C also allows to declare and define functions separately, this is especially needed in case of
library functions. The library functions are declared in header files and defined in library files.
Below is an example declaration.

Parameter Passing to functions


The parameters passed to function are called actual parameters. For example, in the above
program 10 and 20 are actual parameters.
The parameters received by function are called formal parameters. For example, in the above
program x and y are formal parameters.
There are two most popular ways to pass parameters.
Pass by Value: In this parameter passing method, values of actual parameters are copied to
function’s formal parameters and the two types of parameters are stored in different memory
locations. So any changes made inside functions are not reflected in actual parameters of caller.

Pass by Reference Both actual and formal parameters refer to same locations, so any changes
made inside the function are actually reflected in actual parameters of caller.
Parameters are always passed by value in C. For example. in the below code, value of x is not
modified using the function fun().

• C
• C++

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 63
filter_none
edit
play_arrow
brightness_4

#include <stdio.h>

void fun(int x)

x = 30;

int main(void)

int x = 20;

fun(x);

printf("x = %d", x);

return 0;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 64
}

Output:
x = 20

However, in C, we can use pointers to get the effect of pass by reference. For example, consider
the below program. The function fun() expects a pointer ptr to an integer (or an address of an
integer). It modifies the value at the address ptr. The dereference operator * is used to access the
value at an address. In the statement ‘*ptr = 30’, value at address ptr is changed to 30. The
address operator & is used to get the address of a variable of any data type. In the function call
statement ‘fun(&x)’, the address of x is passed so that x can be modified using its address.

• C
• C++
filter_none
edit
play_arrow
brightness_4

# include <stdio.h>

void fun(int *ptr)

*ptr = 30;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 65
}

int main()

int x = 20;

fun(&x);

printf("x = %d", x);

return 0;

Output:
x = 30

Following are some important points about functions in C.


1) Every C program has a function called main() that is called by operating system when a user
runs the program.
2) Every function has a return type. If a function doesn’t return any value, then void is used as
return type. Moreover, if the return type of the function is void, we still can use return statement
in the body of function definition by not specifying any constant, variable, etc. with it, by only

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 66
mentioning the ‘return;’ statement which would symbolise the termination of the function as
shown below:
filter_none
brightness_4

void function name(int a)

....... //Function Body

return; //Function execution would get terminated

3) In C, functions can return any type except arrays and functions. We can get around this
limitation by returning pointer to array or pointer to function.
4) Empty parameter list in C mean that the parameter list is not specified and function can be
called with any parameters. In C, it is not a good idea to declare a function like fun(). To declare
a function that can only be called without any parameter, we should use “void fun(void)”.
As a side note, in C++, empty list means function can only be called without any parameter. In
C++, both void fun() and void fun(void) are same.
5)If in a C program, a function is called before its declaration then the C compiler automatically
assumes the declaration of that function in the following way:
int function name();
And in that case if the return type of that function is different than INT ,compiler would show an
error.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 67
Main Function:
The main function is a special function. Every C++ program must contain a function named
main. It serves as the entry point for the program. The computer will start running the code from
the beginning of the main function.

Types of main Function:


1) The first type is – main function without parameters :

filter_none
brightness_4

// Without Parameters

int main()

...

return 0;

2) Second type is main function with parameters :

filter_none
brightness_4

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 68
// With Parameters

int main(int argc, char * const argv[])

...

return 0;

The reason for having the parameter option for the main function is to allow input from the
command line.

When you use the main function with parameters, it saves every group of characters (separated
by a space) after the program name as elements in an array named argv.

Since the main function has the return type of int, the programmer must always have a return
statement in the code. The number that is returned is used to inform the calling program what the
result of the program’s execution was. Returning 0 signals that there were no problems.

Return by reference in C++ with Examples


Pointers and References in C++ held close relation with one another. The major difference is that
the pointers can be operated on like adding values whereas references are just an alias for
another variable.
• Functions in C++ can return a reference as it’s returns a pointer.
• When function returns a reference it means it returns a implicit pointer.
Return by reference is very different from Call by reference. Functions behaves a very
important role when variable or pointers are returned as reference.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 69
See this function signature of Return by Reference Below:

dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.

Below is the code to illustrate the Return by reference:

filter_none
edit
play_arrow
brightness_4

// C++ program to illustrate return by reference

#include <iostream>

using namespace std;

// Function to return as return by reference

int& returnValue(int& x)

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 70
// Print the address

cout << "x = " << x

<< " The address of x is "

<< &x << endl;

// Return reference

return x;

// Driver Code

int main()

int a = 20;

int& b = returnValue(a);

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 71
// Print a and its address

cout << "a = " << a

<< " The address of a is "

<< &a << endl;

// Print b and its address

cout << "b = " << b

<< " The address of b is "

<< &b << endl;

// We can also change the value of

// 'a' by using the address returned

// by returnValue function

// Since the function returns an alias

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 72
// of x, which is itself an alias of a,

// we can update the value of a

returnValue(a) = 13;

// The above expression assigns the

// value to the returned alias as 3.

cout << "a = " << a

<< " The address of a is "

<< &a << endl;

return 0;

Output:
x = 20 The address of x is 0x7fff3025711c

a = 20 The address of a is 0x7fff3025711c

b = 20 The address of b is 0x7fff3025711c

x = 20 The address of x is 0x7fff3025711c

a = 13 The address of a is 0x7fff3025711c

Explanation:

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 73
Since reference is nothing but an alias(synonym) of another variable, the address
of a, b and x never changes.
Note: We should never return a local variable as a reference, reason being, as soon as the
functions returns, local variable will be erased, however, we still will be left with
a reference which might be a security bug in the code.

Below is the code to illustrate the Return by reference:

filter_none
edit
play_arrow
brightness_4

// C++ program to illustrate return

// by reference

#include <iostream>

using namespace std;

// Global variable

int x;

// Function returns as a return

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 74
// by reference

int& retByRef()

return x;

// Driver Code

int main()

// Function Call for return

// by reference

retByRef() = 10;

// Print X

cout << x;

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 75
return 0;

Output:
10

Explanation:
Return type of the above function retByRef() is a reference of the variable x so value 10 will be
assigned into the x.

Inline Functions in C++

Inline function is one of the important feature of C++. So, let’s first understand why inline
functions are used and what is the purpose of inline function?

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 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 execution time of
small function is less than the switching time.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 76
C++ provides an inline functions to reduce the function call overhead. 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 inline function call. This
substitution is performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small.
The syntax for defining the function inline is:

inline return-type function-name(parameters)

// function code

Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the
request for inlining. Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, 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 function
body.
5) If a function contains switch or goto statement.

Inline functions provide following advantages:


1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal function
calls. Other optimizations can be obtained by considering the flows of calling context and the

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 77
called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-lining
function if variables number which are going to use register increases than they may create
overhead on register variable resource utilization. This means that when inline function body is
substituted at the point of function call, total number of variables used by the function also gets
inserted. So the number of register 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 an
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 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) 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 compiler would require
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 size of the binary
executable file. Thrashing in memory causes performance of computer to degrade.

The following program demonstrates the use of use of inline function.

filter_none
edit
play_arrow
brightness_4

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 78
#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

Function Overloading in C++

Function overloading is a feature in C++ where two or more functions can have the same name
but different parameters.
Function overloading can be considered as an example of polymorphism feature in C++.
Following is a simple C++ example to demonstrate function overloading.

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 79
#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");

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 80
return 0;

Output:
Here is int 10
Here is float 10.1
Here is char* ten

M.KARTHIKA M.Sc.,M.Phil
Vidhyaa Giri College of Arts and Science Page 81

You might also like