Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views55 pages

UNIT-2

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 55

UNIT – II C++ PROGRAMMING

Syllabus
Introduction to C++ - Keywords, Identifiers – Data types – Variables – Operators – Manipulators –
Operator Overloading – Operator Precedence – Control Statements – Functions – Call by Reference –
Arguments – Function Overloading

2.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.
 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.
 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:

1. Object-Oriented Programming: C++ supports object-oriented programming, allowing


developers to create classes and objects and to define methods and properties for these objects.
2. 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.
3. 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.
4. Exception Handling: C++ provides robust exception handling capabilities, making it easier
to write code that can handle errors and unexpected situations.

Simple C++ code examples to help you understand the language:

#include <iostream>

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

Output

Hello, World!
C++ is a middle-level language rendering it the advantage of programming low-level (drivers,
kernels) and even higher-level applications (games, GUI, 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.

Advantages Disadvantages

1. Performance 1. Steep Learning Curve


2. Object-Oriented Programming 2. Verbose Syntax
3. Standard Template Library (STL) 3. Error-Prone
4. Machine Independent
5. Large Community
2.2 Keywords
 Keywords are predefined words that have special meanings to the compiler.
Token
When the compiler is processing the source code of a C++ program, each group of characters
separated by white space is called a token. Tokens are the smallest individual units in a
program. A C++ program is written using tokens. It has the following tokens:
 Keywords
 Identifiers
 Constants
 Strings
 Operators

 Keywords (also known as reserved words) have special meanings to the C++
compiler and are always written or typed in short(lower) cases.
 Keywords are words that the language uses for a special purpose, such as void, int, public,
etc.
 It can’t be used for a variable name or function name or any other identifiers.
 The total count of reserved keywords is 95. Below is the table for some commonly used
C++ keywords.

 asm: To declare that a block of code is to be passed to the assembler.


 auto: A storage class specifier that is used to define objects in a block.
 break: Terminates a switch statement or a loop.
 case: Used specifically within a switch statement to specify a match for the statement’s expression.
 catch: Specifies actions taken when an exception occurs.
 char: Fundamental data type that defines character objects.
 class: To declare a user-defined type that encapsulates data members and operations or member
functions.
 const: To define objects whose value will not alter throughout the lifetime of program execution.
 continue:- Transfers control to the start of a loop.
 default:- Handles expression values in a switch statement that are not handled by case.
 delete: Memory deallocation operator.
 do: indicate the start of a do-while statement in which the sub-statement is executed repeatedly
until the value of the expression is logical-false.
 double: Fundamental data type used to define a floating-point number.
 else: Used specifically in an if-else statement.
 enum: To declare a user-defined enumeration data type.
 extern: An identifier specified as an extern has an external linkage to the block.
 float:- Fundamental data type used to define a floating-point number.
 for: Indicates the start of a statement to achieve repetitive control.
 friend: A class or operation whose implementation can access the private data members of a class.
 goto: Transfer control to a specified label.
 if: Indicate the start of an if statement to achieve selective control.
 inline: A function specifier that indicates to the compiler that inline substitution of the function
body is to be preferred to the usual function call implementation.
 int: Fundamental data type used to define integer objects.
 long: A data type modifier that defines a 32-bit int or an extended double.
 new: Memory allocation operator.
 operator: Overloads a c++ operator with a new declaration.
 private: Declares class members which are not visible outside the class.
 protected: Declares class members which are private except to derived classes
 public: Declares class members who are visible outside the class.
 register: A storage class specifier that is an auto specifier, but which also indicates to the compiler
that an object will be frequently used and should therefore be kept in a register.
 return: Returns an object to a function’s caller.
 short: A data type modifier that defines a 16-bit int number.
 signed: A data type modifier that indicates an object’s sign is to be stored in the high-order bit.
 sizeof: Returns the size of an object in bytes.
 static: The lifetime of an object-defined static exists throughout the lifetime of program execution.
 struct: To declare new types that encapsulate both data and member functions.
 switch: This keyword is used in the “Switch statement”.
 template: parameterized or generic type.
 this: A class pointer points to an object or instance of the class.
 throw: Generate an exception.
 try: Indicates the start of a block of exception handlers.
 typedef: Synonym for another integral or user-defined type.
 union: Similar to a structure, struct, in that it can hold different types of data, but a union can hold
only one of its members at a given time.
 unsigned: A data type modifier that indicates the high-order bit is to be used for an object.
 virtual: A function specifier that declares a member function of a class that will be redefined by
a derived class.
 void: Absent of a type or function parameter list.
 volatile: Define an object which may vary in value in a way that is undetectable to the compiler.
 while: Start of a while statement and end of a do-while statement.

Example: Below is the program for how to use different keywords in the program:

// C++ Program to demonstrate keywords


#include <iostream>
using namespace std;

int main()
{
// Variable declaration and initialization
int n = 2;

// Switch Case Statement


switch (n)
{ // switch keyword
case 1: // case keyword
cout << "Computer Network"
<< endl;
break; // break keyword
case 2:
cout << "C++" << endl;
break;
case 3:
cout << "DBMS" << endl;
break;
default: // default keyword
cout << "Enter Valid number"
<< endl;
}
// Return keyword returns an object to a function's caller
return 0;
}
2.3 Identifiers
Identifiers refer to the name of variables, functions, arrays, classes, etc. created by the
programmer. They are the fundamental requirement of any language.
Rules for naming identifiers:
 Identifier names cannot start with a digit or any special character.
 A keyword cannot be used as an identifier name.
 Only alphabetic characters, digits, and underscores are permitted.
 The upper case and lower case letters are distinct. i.e., A and a are different in C++.
 The valid identifiers are GFG, gfg, and geeks_for_geeks.

Invalid Identifier Bad Identifier Good Identifier

Cash prize C_prize cashprize

catch catch_1 catch1

1list list_1 list1

// C++ program to illustrate the use of identifiers

#include <iostream>
using namespace std;

int main()
{
// Use of Underscore (_) symbol
// in variable declaration
int geeks_for_geeks = 1;

cout << "Identifier result is: " << geeks_for_geeks;


return 0;
}
So there are some main properties of keywords that distinguish keywords from identifiers:

Keywords Identifiers

identifiers are the values used to define different


Keywords are predefined/reserved
programming items like a variable, integers, structures,
words
and unions.

identifiers can start with an uppercase letter as well as


Keywords always start in lowercase
a lowercase letter.

It defines the type of entity. It classifies the name of the entity.

A keyword contains only alphabetical an identifier can consist of alphabetical characters,


characters, digits, and underscores.

It should be lowercase. It can be both upper and lowercase.

No special symbols or punctuations are used in


No special symbols or punctuations are
keywords and identifiers. The only underscore can be
used in keywords and identifiers.
used in an identifier.

2.4 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 they can
store.
 Whenever a 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.
 C++ supports a wide variety of data types and the programmer can select the data type
appropriate to the needs of the application.
 Data types specify the size and types of values to be stored.
 However, storage representation and machine instructions to manipulate each data type differ
from machine to machine, although C++ instructions are identical on all machines.
C++ supports the following data types:
1. Primary or Built-in or Fundamental data type
2. Derived data types
3. User-defined data 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: The keyword used for integer data types is int. Integers typically require 4 bytes of
memory space and range from -2147483648 to 2147483647.
 Character: Character data type is used for storing characters. The keyword used for the character
data type is char. Characters typically require 1 byte of memory space and range 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. The keyword used for the Boolean data type is bool.
 Floating Point: Floating Point data type is used for storing single-precision floating-point values
or decimal values. The keyword used for the floating-point data type is float. Float variables
typically require 4 bytes of memory space.
 Double Floating Point: Double Floating Point data type is used for storing double-precision
floating-point values or decimal values. The keyword used for the double floating-point data type
is double. Double variables typically require 8 bytes of memory space.
 void: Void means without any value. void data type represents a valueless entity. A void data type
is used for those function which does not return a value.
 Wide Character: Wide character data type is also a character data type but this data type has a
size greater than the normal 8-bit data type. Represented by wchar_t. It is generally 2 or 4 bytes
long.
 sizeof() operator: sizeof() operator is used to find the number of bytes occupied by a variable/data
type in computer memory.
2. Derived Data Types: Derived 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
3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by the
user itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined
datatypes:
 Class
 Structure
 Union
 Enumeration
 Typedef defined Datatype

Example:
int m , x[50];
cout<<sizeof(m); //returns 4 which is the number of bytes occupied by the integer variable “m”.
cout<<sizeof(x); //returns 200 which is the number of bytes occupied by the integer array variable
“x”.

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

// C++ Program to Demonstrate the correct size of various data types on your computer.
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;

cout << "Size of long : " << sizeof(long) << endl;


cout << "Size of float : " << sizeof(float) << endl;

cout << "Size of double : " << sizeof(double) << endl;

return 0;
}
Output
Size of char : 1
Size of int : 4
Size of long : 8
Size of float : 4
Size of double : 8
2.5 Variables

Variables in C++ is a name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the variable
effects that memory location.
 In C++, all the variables must be declared before use.

Variable Declaration

// Declaring a single variable


type variable_name;
// Declaring multiple variables:
type variable1_name, variable2_name, variable3_name;

A variable name can consist of alphabets (both upper and lower case), numbers, and the underscore
‘_’ character. However, the name must not start with a number.

// Declaring float variable


float simpleInterest;
// Declaring integer variable
int time, speed;
// Declaring character variable
char var;
int a=50,b=100; //declaring 2 variable of integer type
float f=50.8; //declaring 1 variable of float type
char c='Z'; //declaring 1 variable of char type

Rules for Declaring Variable


 The name of the variable contains letters, digits, and underscores.
 The name of the variable is case sensitive (ex Arr and arr both are different variables).
 The name of the variable does not contain any whitespace and special characters (ex #,$,%,*,
etc).
 All the variable names must begin with a letter of the alphabet or an underscore(_).
 We cannot used C++ keyword(ex float,double,class)as a variable name.

Valid variable names:

int x; //can be letters


int _yz; //can be underscores
int z40;//can be letters

Invalid variable names:

int 89; Should not be a number


int a b; //Should not contain any whitespace
int double;// C++ keyword CAN NOT BE USED

Difference between variable declaration and definition

The variable declaration refers to the part where a variable is first declared or introduced before its
first use. A variable definition is a part where the variable is assigned a memory location and a
value. Most of the time, variable declaration and definition are done together.
See the following C++ program for better clarification:

// C++ program to show difference between definition and declaration of a variable

#include <iostream>

using namespace std;

int main()

// this is declaration of variable a


int a;

// this is initialisation of a

a = 10;

// this is definition = declaration + initialisation

int b = 20;

// declaration and definition of variable 'a123'

char a123 = 'a';

// This is also both declaration and definition as 'c' is allocated memory and

// assigned some garbage value.

float c;

// multiple declarations and definitions

int _c, _d45, e;

// Let us print a variable

cout << a123 << endl;

return 0;

}
Output
a
Time Complexity: O(1)
Space Complexity: O(1)

Types of Variables
There are three types of variables based on the scope of variables in C++
 Local Variables
 Instance Variables
 Static Variables
Types of Variables in C++

Let us now learn about each one of these variables in detail.


1. Local Variables: A variable defined within a block or method or constructor is called a local
variable.
 These variables are created when entered into the block or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is declared.
i.e. we can access this variable only within that block.
 Initialization of Local Variable is Mandatory.
2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor, or block.
 As instance variables are declared in a class, these variables are created when an object of the
class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.
 Initialization of Instance Variable is not Mandatory.
 Instance Variable can be accessed only by creating objects.
3. Static Variables: Static variables are also known as Class variables.
 These variables are declared similarly as instance variables; the difference is that static
variables are declared using the static keyword within a class outside any method constructor
or block.
 Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed automatically
when execution ends.
 Initialization of Static Variable is not Mandatory. Its default value is 0
 If we access the static variable like the Instance variable (through an object), the compiler
will show the warning message and it won’t halt the program. The compiler will replace the
object name with the class name automatically.
 If we access the static variable without the class name, the Compiler will automatically
append the class name.

Instance Variable Vs Static Variable

 Each object will have its own copy of the instance variable whereas We can only have one
copy of a static variable per class irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other objects as
each object has its own copy of the instance variable. In the case of static, changes will be
reflected in other objects as static variables are common to all objects of a class.
 We can access instance variables through object references and Static Variables can be
accessed directly using the class name.
 The syntax for static and instance variables:

class Example
{
static int a; // static variable
int b; // instance variable
}

2.6 Operators

An operator is a symbol that operates on a value to perform specific mathematical or logical


computations.

An operator operates the operands. For example,

int c = a + b;

Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.

Operators in C++ can be classified into 6 types:

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
1) Arithmetic Operators

These operators are used to perform arithmetic or mathematical operations on the operands. For
example, ‘+’ is used for addition, ‘-‘ is used for subtraction ‘*’ is used for multiplication, etc.
Arithmetic Operators can be classified into 2 Types:

A) Unary Operators: These operators operate or work with a single operand.


For example: Increment (++) and Decrement (--) Operators.

Name Symbol Description Example

int a = 5;
Increases the integer value of the variable by
Increment Operator ++ a++; // returns
one
6

Decrement Decreases the integer value of the variable by int a = 5;


--
Operator one a--; // returns 4

Example:
the description
Output
a++ is 10
++a is 12
b-- is 15
--b is 13
Time Complexity: O(1)
Auxiliary Space : O(1)

Note: ++a and a++, both are increment operators, however, both are slightly different.
In ++a, the value of the variable is incremented first and then It is used in the program. In a++, the
value of the variable is assigned first and then It is incremented. Similarly happens for the decrement
operator.
B) Binary Operators: These operators operate or work with two operands. For example: Addition(+),
Subtraction(-), etc.

Name Symbol Description Example

int a = 3, b = 6;
Addition + Adds two operands
int c = a+b; // c = 9

int a = 9, b = 6;
Subtraction – Subtracts second operand from the first
int c = a-b; // c = 3

int a = 3, b = 6;
Multiplication * Multiplies two operands int c = a*b; // c =
18

Divides first operand by the second int a = 12, b = 6;


Division /
operand int c = a/b; // c = 2

Modulo int a = 8, b = 6;
% Returns the remainder an integer division
Operation int c = a%b; // c = 2

Note: The Modulo operator(%) operator should only be used with integers.

Example:

// CPP Program to demonstrate the Binary Operators


#include <iostream>
using namespace std;

int main()
{
int a = 8, b = 3;

// Addition operator
cout << "a + b = " << (a + b) << endl;

// Subtraction operator
cout << "a - b = " << (a - b) << endl;
// Multiplication operator
cout << "a * b = " << (a * b) << endl;

// Division operator
cout << "a / b = " << (a / b) << endl;

// Modulo operator
cout << "a % b = " << (a % b) << endl;

return 0;
}

Output
a + b = 11
a-b=5
a * b = 24
a/b=2
a%b=2
Time Complexity: O(1)
Auxiliary Space : O(1)

2) Relational Operators

These operators are used for the comparison of the values of two operands. For example, ‘>’ checks
if one operand is greater than the other operand or not, etc. The result returns a Boolean value,
i.e., true or false.

Name Symbol Description Example

int a = 3, b = 6;
Is Equal To == Checks if both operands are equal a==b;
// returns false

int a = 3, b = 6;
Checks if first operand is greater than the second
Greater Than > a>b;
operand
// returns false
Name Symbol Description Example

int a = 3, b = 6;
Greater Than or Checks if first operand is greater than or equal to
>= a>=b;
Equal To the second operand
// returns false

int a = 3, b = 6;
Checks if first operand is lesser than the second
Less Than < a<b;
operand
// returns true

int a = 3, b = 6;
Less Than or Checks if first operand is lesser than or equal to
<= a<=b;
Equal To the second operand
// returns true

int a = 3, b = 6;
Not Equal To != Checks if both operands are not equal a!=b;
// returns true

Example:
// CPP Program to demonstrate the Relational Operators
#include <iostream>
using namespace std;
int main()

int a = 6, b = 4;
// Equal to operator
cout << "a == b is " << (a == b) << endl;
// Greater than operator
cout << "a > b is " << (a > b) << endl;
// Greater than or Equal to operator
cout << "a >= b is " << (a >= b) << endl;
// Lesser than operator
cout << "a < b is " << (a < b) << endl;
// Lesser than or Equal to operator
cout << "a <= b is " << (a <= b) << endl;
// true
cout << "a != b is " << (a != b) << endl;
return 0;
}

Output
a == b is 0
a > b is 1
a >= b is 1
a < b is 0
a <= b is 0
a != b is 1
Time Complexity: O(1)
Auxiliary Space : O(1)
Here, 0 denotes false and 1 denotes true.

3) Logical Operators

These operators are used to combine two or more conditions or constraints or to complement the
evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.

Name Symbol Description Example

int a = 3, b = 6;
Returns true only if all the operands are true or
Logical AND && a&&b;
non-zero
// returns true

int a = 3, b = 6;
Returns true if either of the operands is true or
Logical OR || a||b;
non-zero
// returns true

int a = 3;
Logical NOT ! Returns true if the operand is false or zero !a;
// returns false

Example:
// CPP Program to demonstrate the Logical Operators
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;
// Logical AND operator
cout << "a && b is " << (a && b) << endl;

// Logical OR operator
cout << "a ! b is " << (a > b) << endl;

// Logical NOT operator


cout << "!b is " << (!b) << endl;

return 0;
}
Output
a && b is 1
a ! b is 1
!b is 0
Time Complexity: O(1)
Auxiliary Space : O(1)
Here, 0 denotes false and 1 denotes true.

4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. Mathematical operations
such as addition, subtraction, multiplication, etc. can be performed at the bit level for faster
processing.

Name Symbol Description Example

int a = 2, b = 3;
Copies a bit to the evaluated result if it exists
Binary AND & (a & b); //returns
in both operands
2

int a = 2, b = 3;
Copies a bit to the evaluated result if it exists
Binary OR | (a | b); //returns
in any of the operand
3

int a = 2, b = 3;
Copies the bit to the evaluated result if it is
Binary XOR ^ (a ^ b); //returns
present in either of the operands but not both
1
Name Symbol Description Example

int a = 2, b = 3;
Shifts the value to left by the number of bits
Left Shift << (a << 1);
specified by the right operand.
//returns 4

int a = 2, b = 3;
Shifts the value to right by the number of bits
Right Shift >> (a >> 1);
specified by the right operand.
//returns 1

One’s int b = 3;
~ Changes binary digits 1 to 0 and 0 to 1
Complement (~b); //returns -4

Note: Only char and int data types can be used with Bitwise Operators.

Example:
// CPP Program to demonstrate the Bitwise Operators
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Binary AND operator


cout << "a & b is " << (a & b) << endl;

// Binary OR operator
cout << "a | b is " << (a | b) << endl;

// Binary XOR operator


cout << "a ^ b is " << (a ^ b) << endl;

// Left Shift operator


cout << "a<<1 is " << (a << 1) << endl;

// Right Shift operator


cout << "a>>1 is " << (a >> 1) << endl;

// One’s Complement operator


cout << "~(a) is " << ~(a) << endl;

return 0;
}
Output
a & b is 4
a | b is 6
a ^ b is 2
a<<1 is 12
a>>1 is 3
~(a) is -7
Time Complexity: O(1)
Auxiliary Space : O(1)

5) Assignment Operators

These operators are used to assign value to a variable. The left side operand of the assignment operator
is a variable and the right side operand of the assignment operator is a value. The value on the right
side must be of the same data type as the variable on the left side otherwise the compiler will raise an
error.

Namemultiply Symbol Description Example

Assignment Assigns the value on the right to the int a = 2;


=
Operator variable on the left // a = 2

First adds the current value of the


Add and
variable on left to the value on the right int a = 2, b = 4;
Assignment +=
and then assigns the result to the a+=b; // a = 6
Operator
variable on the left

First subtracts the value on the right


Subtract and
from the current value of the variable on int a = 2, b = 4;
Assignment -=
left and then assign the result to the a-=b; // a = -2
Operator
variable on the left

First multiplies the current value of the


Multiply and
variable on left to the value on the right int a = 2, b = 4;
Assignment *=
and then assign the result to the variable a*=b; // a = 8
Operator
on the left

Divide and
First divides the current value of the int a = 4, b = 2;
Assignment /=
variable on left by the value on the right a /=b; // a = 2
Operator
Namemultiply Symbol Description Example

and then assign the result to the variable


on the left

Example:
// CPP Program to demonstrate the Assignment Operators
#include <iostream>
using namespace std;

int main()
{
int a = 6, b = 4;

// Assignment Operator
cout << "a = " << a << endl;

// Add and Assignment Operator


cout << "a += b is " << (a += b) << endl;

// Subtract and Assignment Operator


cout << "a -= b is " << (a -= b) << endl;

// Multiply and Assignment Operator


cout << "a *= b is " << (a *= b) << endl;

// Divide and Assignment Operator


cout << "a /= b is " << (a /= b) << endl;

return 0;
}

Output
a=6
a += b is 10
a -= b is 6
a *= b is 24
a /= b is 6
Time Complexity: O(1)
Auxiliary Space : O(1)

6) Ternary or Conditional Operators(?:)

This operator returns the value based on the condition.


Expression1? Expression2: Expression3
The ternary operator ? determines the answer on the basis of the evaluation of Expression1. If it
is true, then Expression2 gets evaluated and is used as the answer for the expression.
If Expression1 is false, then Expression3 gets evaluated and is used as the answer for the expression.
This operator takes three operands, therefore it is known as a Ternary Operator.
Example:
// CPP Program to demonstrate the Conditional Operators
#include <iostream>
using namespace std;

int main()
{
int a = 3, b = 4;

// Conditional Operator
int result = (a < b) ? b : a;
cout << "The greatest number is " << result << endl;

return 0;
}
Output
The greatest number is 4
Time Complexity: O(1)
Auxiliary Space : O(1)

There are some other common operators available in C++ besides the operators discussed above.
Following is a list of these operators discussed in detail:

A) sizeof Operator: This unary operator is used to compute the size of its operand or variable.
sizeof(char); // returns 1

B) Comma Operator(,): This binary operator (represented by the token) is used to evaluate its first
operand and discards the result, it then evaluates the second operand and returns this value (and type).
It is used to combine various expressions together.
int a = 6;
int b = (a+1, a-2, a+5); // b = 11

C) -> Operator: This operator is used to access the variables of classes or structures.
cout<<emp->first_name;

D) Cast Operator: This unary operator is used to convert one data type into another.
float a = 11.567;
int c = (int) a; // returns 11

E) Dot Operator(.): This operator is used to access members of structure variables or class objects in
C++.
cout<<emp.first_name;

F) & Operator: This is a pointer operator and is used to represent the memory address of an operand.
G) * Operator: This is an Indirection Operator

// CPP Program to demonstrate the & and * Operators


#include <iostream>
using namespace std;

int main()
{
int a = 6;
int* b;
int c;
// & Operator
b = &a;

// * Operator
c = *b;
cout << " a = " << a << endl;
cout << " b = " << b << endl;
cout << " c = " << c << endl;

return 0;
}
Output
a=6
b = 0x7ffe8e8681bc
c=6

H) << Operator: It is called the insertion operator. It is used with cout to print the output.

I) >> Operator: It is called the extraction operator. It is used with cin to get the input.
int a;
cin>>a;
cout<<a;
Time Complexity: O(1)
Auxiliary Space : O(1)

2.7 Manipulators
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.
 Manipulators are special functions that can be included in the I/O statement to alter the format
parameters of a stream.
 Manipulators are operators that are used to format the data display.
 To access manipulators, the file iomanip.h should be included in the program.

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>

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;

// Use of ends Manipulator


cout << "\na";
// NULL character will be added in the Output
cout << "b" << ends;
cout << "c" << endl;

return 0;
}
1. Manipulators with Arguments: Some of the manipulators are used with the argument like setw
(20), setfill (‘*’), and many more. These all are defined in the header file. If we want to use these
manipulators then we must include this header file in our program. For Example, you can use
following manipulators to set minimum width and fill the empty space with any character you
want: std::cout << std::setw (6) << std::setfill (’*’);
 Some important manipulators in <iomanip> are:
1. setw (val): It is used to set the field width in output operations.
2. setfill (c): It is used to fill the character ‘c’ on output stream.
3. setprecision (val): It sets val as the new value for the precision of floating-point values.
4. setbase(val): It is used to set the numeric base value for numeric values.
5. setiosflags(flag): It is used to set the format flags specified by parameter mask.
6. resetiosflags(m): It is used to reset the format flags specified by parameter mask.
 Some important manipulators in <ios> are:
1. showpos: It forces to show a positive sign on positive numbers.
2. noshowpos: It forces not to write a positive sign on positive numbers.
3. showbase: It indicates the numeric base of numeric values.
4. uppercase: It forces uppercase letters for numeric values.
5. nouppercase: It forces lowercase letters for numeric values.
6. fixed: It uses decimal notation for floating-point values.
7. scientific: It uses scientific floating-point notation.
8. hex: Read and write hexadecimal values for integers and it works same as the
setbase(16).
9. dec: Read and write decimal values for integers i.e. setbase(10).
10. oct: Read and write octal values for integers i.e. setbase(10).
11. left: It adjusts output to the left.
12. right: It adjusts output to the right.

There are two types of manipulators used generally:


1] Parameterized and
2] Non-parameterized

1] Parameterized Manipulators: -
Manipulator -> Meaning
setw (int n) -> To set field width to n
setprecision (int p) -> The precision is fixed to p
setfill (Char f) -> To set the character to be filled
setiosflags (long l) -> Format flag is set to l
resetiosflags (long l) -> Removes the flags indicated by l
Setbase(int b) -> To set the base of the number to b
 setw () is a function in Manipulators in C++:
The setw() function is an output manipulator that inserts whitespace between two variables. You
must enter an integer value equal to the needed space.
Syntax:
setw ( int n)
As an example,
int a=15; int b=20;
cout << setw(10) << a << setw(10) << b << endl;
 setfill() is a function in Manipulators in C++:
It replaces setw(whitespaces )’s with a different character. It’s similar to setw() in that it
manipulates output, but the only parameter required is a single character.
Syntax:
setfill(char ch)
Example:
int a,b;
a=15; b=20;
cout<< setfill(‘*’) << endl;
cout << setw(5) << a << setw(5) << a << endl;
 setprecision() is a function in Manipulators in C++:
It is an output manipulator that controls the number of digits to display after the decimal for a
floating point integer.
Syntax:
setprecision (int p)
Example:
float A = 1.34255;
cout <<fixed<< setprecision(3) << A << endl;
 setbase() is a function in Manipulators in C++:
The setbase() manipulator is used to change the base of a number to a different value. The
following base values are supported by the C++ language:
• hex (Hexadecimal = 16)
• oct (Octal = 8)
• dec (Decimal = 10)
The manipulators hex, oct, and dec can change the basis of input and output numbers.

// Example:

#include <iostream>
#include <iomanip>
using namespace std;
main()
{
int number = 100;
cout << "Hex Value =" << " " << hex << number << endl;
cout << "Octal Value=" << " " << oct << number << endl;
cout << "Setbase Value=" << " " << setbase(8) << number << endl;
cout << "Setbase Value=" << " " << setbase(16) << number << endl;
return 0;
}
Output
Hex Value = 64
Octal Value= 144
Setbase Value= 144
Setbase Value= 64

2] Non-parameterized
Examples are endl, fixed, showpoint and flush.
• endl – Gives a new line
• ends – Adds null character to close an output string
• flush – Flushes the buffer stream
• ws – Omits the leading white spaces present before the first field
• hex, oct, dec – Displays the number in hexadecimal or octal or in decimal format
// Example: ws – Omits the leading white spaces present before the first field

#include<iostream>
using namespace std;

int main()

{
char name[125];
cout << "Enter your name" << endl;

cin >> ws;

cin.getline(name,125);

cout << name << endl;

return 0;
}

Output
Enter your name
ram
ram
2.8 Operator Overloading
 C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading.
 Operator overloading is a compile-time polymorphism.
 For example, we can overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +.
 Other example classes where arithmetic operators may be overloaded are Complex
Numbers, Fractional Numbers, Big integers, etc.

Example:

int a;
float b,sum;
sum = a + b;

Implementation:
// C++ Program to Demonstrate the working Logic behind Operator Overloading
class A {
statements;
};

int main()
{
A a1, a2, a3;

a3 = a1 + a2;

return 0;
}

Example of Operator Overloading

// C++ Program to Demonstrate Operator Overloading


#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called when '+' is used with between two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << '\n'; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}

Output
12 + i9

Operator that cannot be overloaded are as follows:

o Scope operator (::)


o Sizeof
o member selector(.)
o member pointer selector(*)
o ternary operator(?:)

Operators that can be Overloaded in C++

 Unary operators

 Binary operators

 Special operators ( [ ], (), etc)


Operators that can be overloaded Examples

Binary Arithmetic +, -, *, /, %

Unary Arithmetic +, -, ++, —

Assignment =, +=,*=, /=,-=, %=

Bitwise & , | , << , >> , ~ , ^

De-referencing (->)

Dynamic memory allocation,


New, delete
De-allocation

Subscript []

Function call ()

Logical &, | |, !

Relational >, < , = =, <=, >=

Important Points about Operator Overloading

1) For operator overloading to work, at least one of the operands must be a user-defined class object.
2) Assignment Operator: Compiler automatically creates a default assignment operator with every
class. The default assignment operator does assign all members of the right side to the left side and
works fine in most cases (this behavior is the same as the copy constructor). See this for more
details.
3) Conversion Operator: We can also write conversion operators that can be used to convert one
type to another type.

4) Any constructor that can be called with a single argument works as a conversion constructor,
which means it can also be used for implicit conversion to the class being constructed.
2.9 Operator Precedence
If there are multiple operators in a single expression, the operations are not evaluated simultaneously.
Rather, operators with higher precedence have their operations evaluated first.
Let us consider an example:
int x = 5 - 17 * 6;
Here, the multiplication operator * is of higher level precedence than the subtraction operator -. Hence,
17 * 6 is evaluated first.
As a result, the above expression is equivalent to
int x = 5 - (17 * 6);
If we wish to evaluate 5 - 17 first, then we must enclose them within parentheses:
int x = (5 - 17) * 6;
Example 1: Operators Precedence
#include <iostream>
using namespace std;
int main() {
// evaluates 17 * 6 first
int num1 = 5 - 17 * 6;
// equivalent expression to num1
int num2 = 5 - (17 * 6);
// forcing compiler to evaluate 5 - 17 first
int num3 = (5 - 17) * 6;
cout << "num1 = " << num1 << endl;
cout << "num2 = " << num2 << endl;
cout << "num3 = " << num3 << endl;
return 0;
}
Output
num1 = -97
num2 = -97
num3 = -72
C++ Operators Precedence Table
The following table (taken from cppreference.com) shows the precedence of C++ operators.
Precedence Level 1 signifies operators of highest priority, while Precedence Level 17 signifies
operators of the lowest priority.
The property of associativity will be discussed shortly.
Precedence Operator Description Associativity
1 :: Scope Resolution Left to Right
2 a++ Suffix/postfix increment Left to Right
a-- Suffix/postfix decrement
type( ) Function cast
type{ } Function cast
a( ) Function call
a[ ] Subscript
. Member access from an object
-> Member access from object ptr
3 ++a Prefix increment Right to Left
--a Prefix decrement
+a Unary plus
-a Unary minus
! Logical NOT
~ Bitwise NOT
(type) C style cast
*a Indirection (dereference)
&a Address-of
sizeof Size-of
co_await await-expression
new new[ ] Dynamic memory allocation
delete Dynamic memory deallocation
delete[]
4 .* Member object selector Left to Right
->* Member pointer selector
5 a*b Multiplication Left to Right
a/b Division
a%b Modulus
6 a+b Addition Left to Right
a-b Subtraction
7 << Bitwise left shift Left to Right
>> Bitwise right shift
8 <=< Three-way comparison operator Left to Right
9 < Less than Left to Right
<= Less than or equal to
> Greater than
>= Greater than or equal to
10 == Equal to Left to Right
!= Not equal to
11 & Bitwise AND Left to Right
12 ^ Bitwise XOR Left to Right
13 | Bitwise OR Left to Right
14 && Logical AND Left to Right
15 || Logical OR Left to Right
16 a?b:c Ternary Conditional Right to Left
throw throw operator
co_yield yield expression (C++ 20)
= Assignment
+= Addition Assignment
-= Subtraction Assignment
*= Multiplication Assignment
/= Division Assignment
%= Modulus Assignment
<<= Bitwise Shift Left Assignment
>>= Bitwise Shift Right Assignment
&= Bitwise AND Assignment
^= Bitwise XOR Assignment
|= Bitwise OR Assignment
17 , Comma operator Left to Right

2.10 Control Statements


Control Statements are used tto execute specific blocks of code primarily based on given situations
and their results.
So basically, in Control Statements, 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 Statement
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
if (condition) {
// code to be executed if the condition is true
}

Flowchart of if

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

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
}
// 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

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-if Ladder in C++

// C++ program to find if the person is child, growing age or adult using if 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 evaluates 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

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


// 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;
}
5. Switch Statement

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++

// 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 OOP


case 'B':
cout << "OOP" << endl;
break;
default:
// if the input character is invalid then print invalid input
cout << "invalid input" << endl;
}
return 0;
}

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++


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

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

// 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
// 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!

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
// 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
2.11 Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the code
once, and use it many times.

Create a Function

C++ provides some pre-defined functions, such as main(), which is used to execute code. But you can
also create your own functions to perform certain actions.

To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():

Syntax
void myFunction() {
// code to be executed
}
Example Explained

 myFunction() is the name of the function


 void means that the function does not have a return value. You will learn more about return
values later in the next chapter
 inside the function (the body), add code that defines what the function should do
Call a Function

Declared functions are not executed immediately. They are "saved for later use", and will be executed
later, when they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
A function can be called multiple times:
Example
void myFunction() {
cout << "I just got executed!\n";
}

int main() {
myFunction();
myFunction();
myFunction();
return 0;
}

// I just got executed!


// I just got executed!
// I just got executed!
Function Declaration and Definition
A C++ function consist of two parts:
 Declaration: the return type, the name of the function, and parameters (if any)
 Definition: the body of the function (code to be executed)
void myFunction() { // declaration
// the body of the function (definition)
}
Note: If a user-defined function, such as myFunction() is declared after the main() function, an error
will occur:
Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error

However, it is possible to separate the declaration and the definition of the function - for code
optimization.

You will often see C++ programs that have function declaration above main (), and function definition
below main (). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();

// The main method


int main() {
myFunction(); // call the function
return 0;
}

// Function definition
void myFunction() {
cout << "I just got executed!";
}
2.12 Call by Reference
In the call-by-reference method, the memory address (reference) of the actual parameter is passed to
the function, allowing direct access and modification of the original values. The actual and the
formal parameters point to the same memory address. Any changes made to the parameters within
the function are directly reflected in the original values outside the function.

Example of Call by Reference


The below example demonstrates the working of call by reference.
// C++ program to demonstrate the working of call by reference
#include <iostream>
using namespace std;
// function to update the original value
void increment(int& num)
{
num++;
cout << num << endl;
}
int main()
{
int number = 5;
increment(number); // Passing 'number' by reference
cout << number << endl;
return 0;
}
Output
6
6

Explanation: In the above code the variable “number” is passed to function increment. A formal
parameter “num” points to the same address as “number”. When the function increments the value of
the parameter, the changes made in “num” is reflected in “number” as we can see from the output.
This is what we say “call by reference”.

Difference between the Call by Value and Call by Reference in C++


The major difference between the two methods of passing the parameters is given below:
Feature Call by Value Call by Reference

In this method, the value of the


In call by reference memory
variable is passed to the
address of the variable is passed.
Value Passed function.

In this method, the original


In this method, the changes
value remains unchanged even
made are reflected in the
when we make changes in the
original variable.
Scope of Changes function.

It may require extra memory It is more memory and time


and time to copy so less efficient as compared to “call by
Performance efficient. value”.

The memory addresses of the The actual and the formal


actual and formal parameters are parameters point at the same
Memory Location different. memory address.
Feature Call by Value Call by Reference

Mainly used to pass values for It is used when we want to


small data or when we do not modify the original value or
Applications want to change original values. save resources.

2.13 Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the function.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:

Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
The following example has a function that takes a string called fname as parameter. When the
function is called, we pass along a first name, which is used inside the function to print the full name:
Example
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the function, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Default Parameter Value
You can also use a default parameter value, by using the equals sign (=).
If we call the function without an argument, it uses the default value ("Norway"):

Example
void myFunction(string country = "Norway") {
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
A parameter with a default value, is often known as an "optional parameter". From the example
above, country is an optional parameter and "Norway" is the default value.
Multiple Parameters
Inside the function, you can add as many parameters as you want:

Example
void myFunction(string fname, int age) {
cout << fname << " Refsnes. " << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
Note that when you are working with multiple parameters, the function call must have the same number
of arguments as there are parameters, and the arguments must be passed in the same order.
2.14 Function Overloading
With function overloading, multiple functions can have the same name with different parameters:
Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
Consider the following example, which have two functions that add numbers of different type:
Example
int plusFuncInt(int x, int y) {
return x + y;
}
double plusFuncDouble(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Instead of defining two functions that should do the same thing, it is better to overload one.

In the example below, we overload the plusFunc function to work for both int and double:

Example
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}

Note: Multiple functions can have the same name as long as the number and/or type of parameters are
different.

You might also like