UNIT-2
UNIT-2
UNIT-2
Syllabus
Introduction to C++ - Keywords, Identifiers – Data types – Variables – Operators – Manipulators –
Operator Overloading – Operator Precedence – Control Statements – Functions – Call by Reference –
Arguments – Function Overloading
#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
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.
Example: Below is the program for how to use different keywords in the program:
int main()
{
// Variable declaration and initialization
int n = 2;
#include <iostream>
using namespace std;
int main()
{
// Use of Underscore (_) symbol
// in variable declaration
int geeks_for_geeks = 1;
Keywords Identifiers
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;
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
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.
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:
#include <iostream>
int main()
// this is initialisation of a
a = 10;
int b = 20;
// This is also both declaration and definition as 'c' is allocated memory and
float c;
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++
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
int c = a + b;
Here, ‘+’ is the addition operator. ‘a’ and ‘b’ are the operands that are being ‘added’.
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:
int a = 5;
Increases the integer value of the variable by
Increment Operator ++ a++; // returns
one
6
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.
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
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:
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.
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.
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;
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.
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 OR operator
cout << "a | b is " << (a | b) << 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.
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
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;
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)
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
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>
int main()
{
istringstream str(" Programmer");
string line;
// Ignore all the whitespace in string
// str before the first word.
getline(str >> std::ws, line);
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.
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.getline(name,125);
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;
}
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
Unary operators
Binary operators
Binary Arithmetic +, -, *, /, %
De-referencing (->)
Subscript []
Function call ()
Logical &, | |, !
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
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
#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.
#include <iostream>
using namespace std;
int main()
{
int num = 5;
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.
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.
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
}
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.
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;
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++.
#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
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()
{
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;
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
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;
}
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();
// 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.
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”.
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.