C
C
They share the same basic syntax. Nearly all of C’s operators and keywords are also
present in C++ and do the same thing.
C++ has a slightly extended grammar than C, but the basic grammar is the same.
Same notions of stack, heap, file-scope and static variables are present in both the
languages.
Below is a table of some of the more obvious and general differences between C and C++. There
are many more subtle differences between the languages and between versions of the languages.
Understanding the differences between C and C++ is crucial for choosing the right programming
language for your projects. The C++ Course covers these differences in detail, helping you make
informed decisions.
C C++
C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
the year 1969 and 1973 at AT&T Bell Labs. 1979.
programming.
Functions in C are not defined inside Functions can be used inside a structure in C+
structures. +.
Namespace features are not present inside Namespace is used by C++, which avoid name
the C. collisions.
Reference variables are not supported by C. Reference variables are supported by C++.
Virtual and friend functions are not Virtual and friend functions are supported by
supported by C. C++.
C provides malloc() and calloc() functions C++ provides new operator for memory
for dynamic memory allocation, allocation and delete operator for memory de-
and free() for memory de-allocation. allocation.
There is no strict type checking in C Strict type checking in done in C++. So many
programming language. programs that run well in C compiler will
C C++
The C++ programming language is used to create applications that will run on a wide variety of
hardware platforms such as personal computers running Windows, Linux, UNIX, and Mac OS. It also
supports the applications for small form factor hardware such as IoT devices like the Raspberry PI
and Arduino–based boards.
The C++ programming language was created by Bjarne Stroustrup in the year 1983, at Bell
Laboratories, USA.
The C++ programming language is said to be the superset of C programming language. The programs
written in C programming language can run in the C++ compiler. The C++ programming language is an
extension of the C programming language.
The programming paradigm is the way of writing computer programs. There are four programming
paradigms and they are as follows.
The Monolithic programming paradigm is the oldest. It has the following characteristics. It is also
known as the imperative programming paradigm.
We use the goto statement to jump from one statement to another statement.
There are no flow control statements like if, switch, for, and while statements in this
paradigm.
This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
It provides the concept of code reusability.
It also provides flow control statements that provide more control to the user.
In this paradigm, all the data is used as global data which leads to data insecurity.
This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
It also provides flow control statements that provide more control to the user.
It follows all the concepts of structure-oriented programming paradigm but the data is
defined as global data, and also local data to the individual modules.
In this paradigm, functions may transform data from one form to another.
The object-oriented programming paradigm is the most popular. It has the following characteristics.
In this paradigm, objects may communicate with each other through function.
In this paradigm, programs are divided into what are known as objects.
It introduces concepts like data abstraction, inheritance, and overloading of functions and
operators overloading.
Procedure-oriented Object-oriented
It follows the top-bottom flow of execution. It follows the bottom-top flow of execution.
Larger programs have divided into smaller modules The larger program has divided into objects.
called as functions.
The main focus is on solving the problem. The main focus is on data security.
There is no concept of friend function and virtual It has the concept of friend function and
functions. virtual functions.
1. **Variables and Data Types**: The building blocks for storing and manipulating data, such as `int`,
`float`, `char`, and `bool`.
2. **Operators**: Symbols that perform operations on variables and values, including arithmetic (`+`,
`-`, `*`, `/`, `%`), comparison (`==`, `!=`, `>`, `<`), and logical (`&&`, `||`, `!`) operators.
3. **Control Structures**: These include `if`, `else`, `while`, `for`, and `switch` statements, which
control the flow of the program based on certain conditions.
4. **Functions**: Blocks of code that perform specific tasks and can be called from other parts of the
program. Functions can return values and take parameters.
5. **Arrays and Strings**: Collections of elements stored in a single variable. Arrays hold multiple
values of the same type, while strings are arrays of characters.
6. **Pointers and References**: Variables that store the memory address of another variable. They
are essential for dynamic memory allocation and manipulating data directly in memory.
7. **Classes and Objects**: The foundation of Object-Oriented Programming (OOP) in C++. Classes
define the blueprint for objects, encapsulating data and functions together.
8. **Inheritance and Polymorphism**: Key OOP concepts that allow classes to inherit properties and
behaviors from other classes (inheritance), and for objects to be treated as instances of their parent
class (polymorphism).
9. **Templates**: Enable generic programming by allowing functions and classes to operate with
different data types without being rewritten for each type.
10. **Standard Template Library (STL)**: A powerful set of C++ template classes to provide general-
purpose classes and functions, such as vectors, lists, queues, and algorithms.
These components form the backbone of C++ programming, allowing developers to create efficient,
robust, and scalable software. If you'd like to dive deeper into any of these topics, just let me know!
OOP Concepts
PREVIOUS
NEXT
The main aim of the C++ programming language was to add the concepts of object-oriented
programming paradigm to the procedure-oriented programming paradigm like C programming
language. The following are the object-oriented programming concepts.
Object
Class
Encapsulation
Abstraction
Inheritance
Polymorphism
Object
An object is any real-time entity with some properties and behaviors. The object is the basic unit of
the object-oriented programming paradigm. The properties of an object are the data values, and the
behaviors are the functionalities that are associated with it. In object-oriented programming, the
objects are created through the concept of class.
Class
A class is a collection of data and code where data is defined as variables and code like methods. By
creating the class, we can define a blueprint of an object. Every class in OOPs defines a user-defined
data type. The data and code defined in a class are said to be the members of that class (data
members and member functions respectively).
Encapsulation
Encapsulation is the process of combining data with code into a single unit (class/object). We use the
concept of class and object to implement encapsulation. The encapsulation aims to avoid the access
of private data members from outside the class. So it binds the data members with member
functions.
Abstraction
Abstraction is the process of hiding unnecessary details and showing only useful details to the end-
user. Using the abstraction concept, the actual business logic is hidden from the users and shown
only required things to solve the problem.
Inheritance
Inheritance is the process of acquiring properties from one object to another object. In other words,
inheritance is the process of deriving a new class from an existing class where the members of the
existing class are extended to the newly derived class. Here, the existing class is called a base class or
a superclass or a parent class, and the newly created class is called a derived class or a subclass or a
child class. The inheritance concept enables a major feature called code reusability.
Polymorphism
Polymorphism is the process of defining a single function with different functionalities (or)
definitions. It is implemented using the concepts of function overloading and overriding. In C++, we
also have a feature of operator overloading.
PREVIOUS
NEXT
The C++ programming language supports both procedure-oriented and object-oriented programming
paradigms. So, we can write a C++ program using the POP structure and OOP structure too.
We use the following general structure to write C++ programs using Procedure-Oriented
Programming Paradigm.
Explain
/*documentation*/
pre-processing statements
global declaration;
void main()
Local declaration;
Executable statements;
function body
Explain
void main()
int c;
void get_data();
get_data();
c = sum(a, b);
void get_data()
return a + b;
We use the following general structure to write C++ programs using Object-Oriented Programming
Paradigm.
Explain
/*documentation*/
class ClassName
{
member variable declaration;
member functions(){
function body
};
void main ()
ClassName object;
object.member;
Explain
class Addition{
int a, b;
public:
get_data(){
int sum(){
get_data();
return a + b;
}
};
void main(){
Addition obj;
The data type is a category of data. In other words, a data type is a collection of data values with
similar characteristics. In the C++ programming language, every variable needs to be created with a
data type.
The data type of a variable specifies the following.
An integer is a number without a decimal part. For example, the value 10 is an integer. In c++ integer
data type has the following characteristics.
The integer value is represented using the type specifier “%d” or “%i".
The integer data type allows storing any value in the range from -32768 to 32767. However,
it may change using type modifier.
Floating-point Data type
A floating-point value is a number with a decimal part. For example, the value 10.65 is a floating-
point. In c++ floating-point data type has the following characteristics.
The floating-point data type allows storing any value in the range from 2-31 to 231.
The double data type is similar to the floating-point data type but it allows a wide range of values.
The double data type has the following characteristics.
The double data type allows storing any value in the range from 2-63 to 263.
The double data type does not allows type modifier except long.
The double data type allows double precision upto 12 decimal points.
A character is a symbol enclosed in a single quotation. Here, the symbol may be anything like an
alphabet, a digit, or a special symbol. In C++, the character data type has the following
characteristics.
The character value is represented using the type specifier “%c” or "%s".
The character data type allows storing any value in the range from -128 to 127.
The character data type allows only signed and unsigned type modifiers.
The boolean data type contains only two values 0 and 1. Here the value 0 represents false, and 1
represents true. The boolean data type has the following characteristics.
The void data type is a value less data type, and it represents nothing. The void data type has the
following characteristics.
The void data type does not allows storing any value.
The wide-character data type is similar to character data type, but it takes 2 bytes of memory. It
allows a wide range of character values compare to the character data type. This data type has
supported by the latest compilers only. The keyword wchar_t is used to represent wide character
data type.
Signed Integer int or short int or long int %d or %i 2 or 4 bytes -32768 to +32767 or 2-31 to 231
Double double or long double %ld 8 bytes +/- 1.7e +/- 308 (~15 digits)
1. Create a Source File: Write your C++ code in a text editor and save the file with a .cpp
extension, e.g., hello.cpp.
cpp
#include <iostream>
int main() {
return 0;
2. Choose a Compiler: You need a C++ compiler to compile your code. Popular choices include
GCC (GNU Compiler Collection) and Clang.
3. Open a Command Line Interface: On Windows, you can use Command Prompt or
PowerShell. On macOS and Linux, you can use Terminal.
4. Navigate to the Directory: Use the cd command to change to the directory where your
source file is located.
5. Compile the Program: Run the compiler with your source file. For GCC, the command looks
like this: sh g++ -o hello hello.cpp
This command tells GCC to compile hello.cpp and output an executable named hello.
6. Run the Executable: After successfully compiling, you can run the program by typing the
name of the executable:
o On Windows:
sh
hello.exe
sh
./hello
If everything is set up correctly, you should see the output:
Hello, World!
Alternatively, you can use an IDE like Visual Studio, Code::Blocks, or Eclipse, which can handle the
compilation and execution process for you, making it more straightforward.
C++ Variables
A variable is named memory location, where the user can store different values of the specified data
type. In simple words, a variable is a value holder. Every variable in the program has the following
properties.
Every variable is allocated with a memory based on the data type of it.
Creating Variables
Creating a variable is nothing but declaring a variable. In C++, all the variables must be declared
before they use in the program. The general syntax for declaring a variable is as follows.
data_type variable_name;
The above syntax is used to declare a variable without initial value. But, C++ allows us to declare a
variable with initial value too. And it can be done using the following syntax.
In C++, multiple variables of the same data type may be declared using a single statement. In this
case, all the variables must be separated with a comma symbol. Let's look at the following
declaration statements.
int a, b, c;
float x = 10.5, y;
Every declaration statement with multiple variables may contain declaration without initial value or
with an initial value or mix-up of both.
Types of Variables
Based on the location of variable declaration, variables are classified into five types. They are as
follows.
Local Variables
Global Variables
Formal Variables
Member Variables
Instance Variables
Local Variables
The variables that are declared inside a function or a block are called local variables. The local
variable is visible only inside the function or block in which it is declared. That means the local
variables can be accessed by the statements that are inside the function or block in which the
variable has declared. Outside the function or block, the local variable can't be accessible.
The local variables are created upon execution control enters into the function or block and
destroyed upon exit.
Explain
int sum(){
return a + b;
int main()
int result;
result = sum();
//cout << a << "+" << b << "=" << sum() << endl; // Error - a & b are not accessible
return 0;
Global Variables
The variables that are declared outside a function are called global variables. The global variable is
visible inside all the functions that are defined after its declaration. That means the global variables
can be accessed by all the functions that are created after the global variable declaration. The
functions that have created before the global variable declaration can't access it.
The local variables are created upon execution starts and destroyed upon exit.
Explain
#include <iostream>
int main()
void show();
show();
return 0;
}
void show(){
cout << "a = " << a << endl; // refer to local variable
cout << "a = " << : :a << endl; // refer to global variable
When both global and local variables has same name, only local variable is refered inside the
function. To refer the global variable we need to use : : (scope resolution) operator.
Formal Variables
The variables that are created in the function definition as receivers to the parameter values are
called formal variables. The formal variables are also known as formal parameters, and they act as
local variables inside the function.
Explain
#include <iostream>
int main()
add(a, b);
return 0;
In the above example program, the variables x and y are called formal variables.
The formal variables are allowed only when the function has parameters.
Member Variables
The variables that are created in a class are known as member variables. The member variables are
accessible to all the methods of that class. The member variables are also accessible to the methods
of other classes using inheritance mechanism.
Explain
#include <iostream>
class Sample{
public:
int a, b;
void setData(){
void getData(){
cout << "a = " << a << endl << "b = " << b << endl;
};
int main()
Sample s;
s.setData();
s.getData();
return 0;
In the above example program, the variables a and b are called member variables of class Sample.
Instance Variables
The instance variable is a special type of variable of a user-defined data type called class. That means
an instance variable is a variable of class type. The instance variables are also known as objects. The
instance variables are used to access the class members from outside the class.
Explain
#include <iostream>
class Sample{
public:
int a, b;
void setData(){
void getData(){
cout << "a = " << a << endl << "b = " << b << endl;
};
int main()
{
Sample s;
s.setData();
s.getData();
return 0;
In the above example program, the variable s in the main method is called instance variable of class
Sample, and it also is known as the object of Sample class.
C++ Expressions
An expression is collection of operators and operands which produce a unique value as result. The
expressions are used to perform mathematical and logical operations in a program. In an expression
operator is a symbol with pre-defined task and operands are the data values on which the operation
is performed.
Infix Expression
Prefix Expression
Postfix Expression
Infix Expression
Prefix Expression
Postfix Expression
C++ Operators
PREVIOUS
NEXT
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operators
Other Operators
The arithmetic operators are the symbols that are used to perform basic mathematical operations
like addition, subtraction, multiplication, division and percentage modulo. The following table
provides information about arithmetic operators.
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
The formal variables are allowed only when the function has parameters.
The remainder of the division operator is used with integer data type only.
The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational operator
has two results TRUE or FALSE. In simple words, the relational operators are used to define
conditions in a program. The following table provides information about relational operators.
Operator Meaning Example
< Returns TRUE if the first value is smaller than second value otherwise returns 10 < 5 is FALSE
FALSE
> Returns TRUE if the first value is larger than second value otherwise returns 10 > 5 is TRUE
FALSE
<= Returns TRUE if the first value is smaller than or equal to second value otherwise 10 <= 5 is FALSE
returns FALSE
>= Returns TRUE if the first value is larger than or equal to second value otherwise 10 >= 5 is TRUE
returns FALSE
== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.
&& Logical AND - Returns TRUE if all conditions are TRUE otherwise 10 < 5 && 12 > 10 is
returns FALSE FALSE
|| Logical OR - Returns FALSE if all conditions are FALSE otherwise 10 < 5 || 12 > 10 is TRUE
returns TRUE
! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if !(10 < 5 && 12 > 10) is
it is TRUE TRUE
Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE
then complete condition becomes FALSE.
Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.
The increment and decrement operators are called unary operators because both need only one
operand. The increment operators adds one to the existing value of the operand and the decrement
operator subtracts one from the existing value of the operand. The following table provides
information about increment and decrement operators.
a++; ⇒ a = 6
a--; ⇒ a = 4
-- Decrement - Subtracts one from existing value int a = 5;
The increment and decrement operators are used infront of the operand (++a) or after the operand
(a++). If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is
used after the operand, we call it as post-increment or post-decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the
expression evaluation. That means, when we use pre-increment or pre-decrement, first the value of
the variable is incremented or decremented by one, then the modified value is used in the
expression evaluation.
Example code
Explain
#include <iostream>
int main()
int i = 5, j;
j = ++i; // Pre-Increment
cout << "i = " << i << ", j = " << j << endl;
return 0;
Output
Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one.
Example code
Explain
#include <iostream>
int main()
int i = 5, j;
j = i++; // Post-Increment
cout << "i = " << i << ", j = " << j << endl;
return 0;
Output
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the C++ programming
language.
⇒ A = A+10
+= Add both left and right-hand side values and store the result into left-hand side A += 10
variable
⇒ A = A-B
-= Subtract right-hand side value from left-hand side variable value and store the A -= B
result
into left-hand side variable
⇒ A = A*B
*= Multiply right-hand side value with left-hand side variable value and store the A *= B
result
into left-hand side variable
⇒ A = A/B
/= Divide left-hand side variable value with right-hand side variable value and store A /= B
the result
into the left-hand side variable
⇒ A = A%B
%= Divide left-hand side variable value with right-hand side variable value and store A %= B
the remainder
into the left-hand side variable
The bitwise operators are used to perform bit-level operations in the c++ programming language.
When we use the bitwise operators, the operations are performed based on the binary values. The
following table describes all the bitwise operators in the C++ programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
⇒ 16 (10000)
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 29 (11101)
| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B
⇒ 13 (01101)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 6 (00110)
~ the result of Bitwise once complement is negation of the bit (Flipping) ~A
⇒ 100 (1100100)
<< the Bitwise left shift operator shifts all the bits to the left by the specified A << 2
number of positions
⇒ 6 (00110)
>> the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
number of positions
Example code
The scope resolution operator in C++ is used to access the global variable when both local and global
variables are having the same name, to refer to the static members of a class, and to define a
function definition outside the class. We discuss in detail about scope resolution operator in the later
tutorial in this series.
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This operator
is used with the following syntax.
sizeof(variableName);
Example code
This operator is used to separate variables while they are declaring, separate the expressions in
function calls, etc.
Unary Operators
Binary Operators
Ternary Operators
PREVIOUS
NEXT
In the C++ programming language, an expression is evaluated based on the operator precedence and
associativity. When there are multiple operators in an expression, they are evaluated according to
their precedence and associativity. The operator with higher precedence is evaluated first and the
operator with the least precedence is evaluated last.
To understand expression evaluation in c, let us consider the following simple example expression.
Example code
10 + 4 * 3 / 2
In the above expression, there are three operators +, * and /. Among these three operators, both
multiplication and division have the same higher precedence and addition has lower precedence. So,
according to the operator precedence both multiplication and division are evaluated first and then
the addition is evaluated. As multiplication and division have the same precedence they are
evaluated based on the associativity. Here, the associativity of multiplication and division is left to
right. So, multiplication is performed first, then division and finally addition. So, the above expression
is evaluated in the order of * / and +. It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
Operator Precedance
In any programming language, every operator has provided a preference that is used at the time of
expression evaluation. In C++, the following list provides the operators' preference from higher to
lower.
5. Relational operators
6. Assignment operators
PREVIOUS
NEXT
Type conversion is the process of converting a data value from one data type to another data type.
In the C++ programming language, the data conversion is performed in two different methods and
they are as follows.
The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler. Sometimes type conversion is also called implicit type
conversion. The implicit type conversion is automatically performed by the compiler.
For example, in c programming language, when we assign an integer value to a float variable the
integer value automatically gets converted to float value by adding decimal value 0. And when a float
value is assigned to an integer variable the float value automatically gets converted to an integer
value by removing the decimal value. To understand more about type conversion observe the
following...
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
Example code
Explain
#include <iostream>
int i = 95 ;
float f = 90.99 ;
char ch = 'A' ;
return 0;
Typecasting is also called an explicit type conversion. Compiler converts data from one data type to
another data type implicitly. When compiler converts implicitly, there may be a data loss. In such a
case, we convert the data from one data type to another data type using explicit type conversion. To
perform this we use the unary cast operator. To convert data from one type to another type we
specify the target data type in parenthesis as a prefix to the data value that has to be converted. The
general syntax of typecasting is as follows.
(TargetDatatype) DataValue
Example
In the above example code, both totalMarks and maxMarks are integer data values. When we
perform totalMarks / maxMarks the result is a float value, but the destination (average) datatype is a
float. So we use type casting to convert totalMarks and maxMarks into float data type.
Example code
Explain
#include <iostream>
int main()
int a, b, c ;
float avg ;
avg = (a + b + c) / 3 ;
cout << "avg before type casting = " << avg << endl;
avg = (float)(a + b + c) / 3 ;
cout << "avg after type casting = " << avg << endl;
return 0;
C++ Pointers
PREVIOUS
NEXT
Before beginning to learning about pointers, we need to understand how the variables are managed
in a program.
Little info about variables
In the c++ programming language, we use normal variables to store user data values. When we
declare a variable, the compiler allocates required memory with the specified name. In the c++
programming language, every variable has a name, datatype, value, storage class, and address.
In c++ programming language, we use the reference operator "&" to access the address of the
variable. For example, to access the address of a variable marks, we use &marks. Look at the
following code to display the memory location address of a variable marks.
Example code
Explain
#include <iostream>
int main()
cout << "Address of marks -> " << &marks << endl;
cout << "Value of marks -> " << marks << endl;
return 0;
Output
What is a pointer?
We use a special type of variable called a pointer to store the address of another variable with the
same datatype. A pointer is defined as follows...
Pointer is a special type of variable used to store the memory location address of a variable.
In the c++ programming language, we can create pointer variables of any datatype. Every pointer
stores the address of the variable with the same datatype only. That means the integer pointer is
used to store the address of the integer variable only.
In c++ programming language, the declaration of a pointer variable is similar to the variable creation,
but the name of the pointer variable must prefix with the symbol *. We use the following syntax to
declare a pointer variable.
Syntax
data_type *pointerName;
Example
int *ptr;
In the above example declaration, the variable "ptr" is a pointer variable that holds any integer
variable address.
The pointer variable used to store the address of another variable of the same data type. It is also
used to access the address and value of the variable to which it points. Look at the following code to
illustrate the pointer use.
Example code
Explain
#include <iostream>
int main()
cout << "Address of marks -> " << ptr << endl;
cout << "Value of marks -> " << *ptr << endl;
return 0;
Output
Every pointer variable is used to store the address of another variable. In computer memory address
of any memory location is an integer value. In c programming language, integer requires 4 bytes of
memory. So, irrespective of pointer datatype every pointer variable is allocated with 4 bytes of
memory.
Example code
Explain
#include <iostream>
int main()
int *intPtr;
double *doublePtr;
char *charPtr;
cout << "Memory size of integer pointer intPtr -> " << sizeof(intPtr) << endl;
cout << "Memory size of double pointer doublerPtr -> " << sizeof(doublePtr) << endl;
cout << "Memory size of character pointer charPtr -> " << sizeof(charPtr) << endl;
return 0;
}
Output
void Pointer
In C++, void pointer is a pointer variable that is independent of data type. A void pointer is used to
store the address of a variable of any datatype. We use the keyword "void" to create void pointer.
Example code
Explain
#include <iostream>
int main()
int intVariable;
float floatVariable;
void *anyPtr;
anyPtr = &intVariable;
cout << "Address of integer variable -> " << anyPtr << endl;
cout << "Address of the pointer itself -> " << &anyPtr << endl;
anyPtr = &floatVariable;
cout << "Address of float variable -> " << anyPtr << endl;
cout << "Address of the pointer itself -> " << &anyPtr << endl;
return 0;
Output
C++ Arrays
PREVIOUS
NEXT
An array is a special type of variable used to store multiple values of same data type at a time.
When we work with a large number of data values, we need any number of different variables. As
the number of variables increases, the complexity of the program also increases. There may be
situations where we need to work with a large number of similar data values. This work made easy
with the concept called "Array" in C++.
What is an Array?
An array is a special type of variable used to store multiple values of same data type at a time. An
array may aslo defines as a collection of similar data items stored in continuous memory locations
with single name.
When we want to create an array, we must know the data type of values to be stored and also the
number of values to be stored. We use the following syntax to create an array.
Syntax
Explain
data_type arrayName[size];
or
or
In the above syntax, the data_type specifies the type of values we store in that array, and size
specifies the maximum number of values that the array stores. We may use any syntax to create an
array.
When an array is created without any specific size, it must be initialized. However, it is
optional to initialize if the size has been specified.
When an array is created without a specific size, then the size of that array is decided by the
compiler based on the number of data values initialized.
Example
string fruits[5];
In the above example, the "mobiles" array was created without any size. But initialized with 6
elements, so the size of it is decided by the compiler as 6.
When an array has been created, it allocated with the memory as follows.
The individual elements of an array are identified using the combination of 'arrayName' and 'index
number'. We use the syntax like arrayName[indexNumber] to represent an individual element of an
array. Using the same we may access or change the element value.
The individual elemetns of the colors array are accessed as shown in the below figure.
Example code
Explain
#include <iostream>
int main()
cout << "First element is " << colors[0] << endl; // Accessing the first element
return 0;
Output
We use the for statement to loop through an array. check the following code to loop through the
array colors.
Example code
Explain
#include <iostream>
int main()
{
cout << "colors[" << i << "] = " << colors[i] << endl;
return 0;
Output
In C++, there is no bondary checking. We may access the memory locations beyond the index
numbers which lead to unexcepted results.
When an array is created with specific size and initial values then number of values must
equal or less than the size but not more than the size.
Address of the first element is called base address and it is store in a pointer with the array
name automatically.
PREVIOUS
NEXT
The array name itself acts as a pointer to the first element of that array.
In the c++ programming language, when we declare an array, the compiler allocates the required
amount of memory and also creates a constant pointer with the array name and stores the base
address of that pointer in it. The address of the first element of an array is called a base address of
that array.
That means the array name itself acts as a pointer to the first element of that array.
We can use the array name to access the address and value of all the elements of that array.
Explain
#include <iostream>
int main()
cout << "Base address is " << colors << endl; // array name as pointer
cout << "colors[3] = " << *(colors+3) << endl; // Accessing value using pointer array
return 0;
Output
In the above example, the array name colors can be used as follows.
Addresses
Values
C++ Strings
PREVIOUS
NEXT
A string is an object of built-in class string that holds a sequence of characters surrounded by double
quotes.
A string is a sequence of characters surrounded by double quotes. The C++ programming language
supperts the following two types of string concepts.
In C++, a string may define as a character array. A character array is simply an array of characters that
is terminated by a null character "\0".
Example
Explain
#include <iostream>
int main()
The C++ compiler automatically places the '\0' at the end of the string when it initializes the
array.
A character array string allows us to access individual characters of the string using index
numbers.
The C++ standard library provides a built-in class string. The string class allows us to create an object
that holds a sequence of characters - string.
Example code
Explain
#include <iostream>
int main()
cout << "Hello, " << name << endl; // Accessing hole string
return 0;
}
String handling functions in C++
The C++ has a standard library header file string.h. The string.h provides various built-in functions to
work with string values.
strlen(string s)
- Used to find the length of a string (total number of characters)
int capacity(string s)
- It returns the capacity allocated to the string s, which can be equal to or more than the size
of the string.
swap(string s)
- It returns the capacity allocated to the string s, which can be equal to or more than the size
of the string.
resize(int newSize)
- It changes the size of string, the size can be increased or decreased.
shrink_to_fit()
- It decreases the capacity of the string and makes it equal to the minimum capacity of the
string.
Example
Explain
#include <iostream>
int main()
{
string name = "Rama"; // string as an object
cout << "Length of the name => " << name.length() << endl;
cout << "Capacity of the message => " << name.capacity() << endl;
cout << "Before swap => name = " << name << ", message = " << message << endl;
message.swap(name);
cout << "After swap => name = " << name << ", message = " << message << endl;
return 0;
Output
C++ if Statement
PREVIOUS
NEXT
In c++, the if statement is used to make decisions based on a condition. The if statement verifies the
given condition and decides whether a block of statements to be executed or not based on the
condition result. The if statement has the following forms.
if statement
if-else Statement
if-else if Statement
if Statement
The if statement checks the given condition and executes the block of code if the condition is
evaluated to true. In other words, the if statement is used to execute a block of code if the given
condition is true.
Syntax - if Statement
if (condition) {
The condition must be evaluated to either true or false. In C++, any non-zero value is considered to
be true and zero as false.
Explain
#include <iostream>
int main()
int a = 10;
if(5) {
if(0) {
if(a = 30) {
if(a = 30, 0) {
if(a = 30, 0, 9) {
return 0;
Output
if-else Statement
The if-else statement checks the given condition and executes a block of code if the condition is true
otherwise, executes another block of code defined under else.
Explain
if (condition) {
} else {
The condition must be evaluated to either true or false. In C++, any non-zero value is considered to
be true and zero as false.
Explain
#include <iostream>
if(a < b) {
cout << a << " is smaller than " << b << endl;
} else {
cout << a << " is larger than " << b << endl;
return 0;
Output
if-else if Statement
The if-elseif statement used to check a new condition in the elseif if the first condition is evaluated to
false. The elseif statement must follw the if statement.
Explain
if (condition_1) {
} else if (condition_2) {
Explain
#include <iostream>
using namespace std;
int main()
cout << a << " is larger than " << b << " and " << c << endl;
cout << b << " is larger than " << a << " and " << c << endl; // executed
} else {
cout << c << " is larger than " << a << " and " << b << endl;
return 0;
Output
PREVIOUS
NEXT
Using the switch statement, one can select only one option from more number of options. In the
switch statement, we provide a value that is compared with a value associated with each option.
Whenever the given value matches the value associated with an option, the execution starts from
that option. In the switch statement, each option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
Syntax - if Statement
Explain
switch (key_value) {
case value_1:
// block of code 1
break;
case value_2:
// block of code 2
break;
case value_3:
// block of code 3
break;
case value_4:
// block of code 4
break;
...
Explain
#include <iostream>
int main()
int key_value;
switch( key_value ) {
break ;
break ;
break ;
break ;
break ;
break ;
break ;
break ;
break ;
return 0;
Output
The case values must be either integer or character or boolean but not any other data type
like string, float, double, etc,.
The expression provided in the switch should result in a constant value of integer or
character or boolean otherwise it would not be valid.
Both switch and case are keywords so they must be used only in lower case letters.
The data type of case value and the value specified in the switch statement must be the
same.
The keyword case and its value must be superated with a white space.
The case values need not be defined in sequence, they can be in any order.
The default case is optional and it can be defined anywhere inside the switch statement.
The switch value might be direct, a variable or an expression.
PREVIOUS
NEXT
It's quite common that errors may occur during file operations. There may have different reasons for
arising errors while working with files. The following are the common problems that lead to errors
during file operations.
When trying to read from a file beyond its total number of characters.
When trying to perform a read operation from a file that has opened in write mode.
When trying to perform a write operation on a file that has opened in reading mode.
During the file operations in C++, the status of the current file stream stores in an integer flag defined
in ios class. The following are the file stream flag states with meaning.
We use the above flag bits to handle the errors during the file operations.
The C++ programming language provides several built-in functions to handle errors during file
operations. The file error handling
int bad() It returns a non-zero (true) value if an invalid operation is attempted or an unrecoverable error has occurred
may be possible to recover from any other error reported and continue operations.
int fail( ) It returns a non-zero (true) value when an input or output operation has failed.
int It returns a non-zero (true) value when no error has occurred; otherwise returns zero (false).
good()
Function Return Value
int eof( ) It returns a non-zero (true) value when end-of-file is encountered while reading; otherwise returns zero (fals
int bad( )
The bad( ) function returns a non-zero (true) value if an invalid operation is attempted or an
unrecoverable error has occurred. Returns zero if it may be possible to recover from any other error
reported and continue operations.
Explain
#include <iostream>
#include <fstream>
int main()
fstream file;
file.open("my_file.txt", ios::out);
string data;
if(!file.bad()){
cout << "Status of the badbit: " << file.bad() << endl;
else {
cout << "Data read from file - " << data << endl;
}
return 0;
Output
int fail( )
The fail( ) function returns a non-zero value when an input or output operation has failed.
Explain
#include <iostream>
#include <fstream>
int main()
fstream file;
file.open("my_file.txt", ios::out);
string data;
if(file.fail()){
cout << "Status of the failbit: " << file.fail() << endl;
else {
cout << "Data read from file - " << data << endl;
return 0;
Output
int eof( )
The eof( ) function returns a non-zero (true) value when end-of-file is encountered while reading;
otherwise returns zero (false).
Explain
#include <iostream>
#include <fstream>
int main()
fstream file;
file.open("my_file.txt", ios::in);
string data;
while(!file.eof()){
cout << "data read: " << data << " | eofbit: " << file.eof() << endl;
}
return 0;
Output
int good( )
The good( ) function returns a non-zero (true) value when no error has occurred; otherwise returns
zero (false).
Explain
#include <iostream>
#include <fstream>
int main()
fstream file;
file.open("my_file.txt", ios::in);
string data;
cout << endl << "Data read from file:" << endl;
while(!file.eof()){
return 0;
Output
int clear( )
The clear( ) function used to reset the error state so that further operations can be attempted.
The above functions can be summarized as eof() returns true if eofbit is set; bad() returns
true if badbit is set. The fail() function returns true if failbit is set; the good() returns true
there are no errors. Otherwise, they return false.
All the built-in function returns either non-zero to indicate true or zero to indicate false.
C++ Formatted IO
PREVIOUS
The iomanip.h and iostream.h header files are used to perform the formatted IO operations in C++.
The C++ programming language provides the several built-in functions to display the output in
formatted form. These built-in functions are available in the header file iomanip.h and ios class of
header file iostream.h.
The ios class contains several member functions that are used to perform formmated IO operations.
The ios class also contains few format flags used to format the output. It has format flags
like showpos, showbase, oct, hex, etc. The format flags are used by the function setf( ).
The following table provides the details of the functions of ios class used to perform formatted IO in
C++.
Function Description
width(int) Used to set the width in number of character spaces for the immediate output data.
fill(char) Used to fill the blank spaces in output with given character.
precision(int) Used to set the number of the decimal point to a float value.
setf(format flags) Used to set various flags for formatting output like showbase, showpos, oct, hex, etc.
All the above functions are called using the built-in object cout.
Lets look at the following code to illustrate the formatted IO operations using member functions of
ios class.
Explain
#include <iostream>
#include <fstream>
int main()
cout.width(5);
cout.width(5);
cout.fill('*');
cout.setf(ios::showpos);
cout.unsetf(ios::showpos);
return 0;
Output
The iomanip.h header file contains several special functions that are used to perform formmated IO
operations.
The following table provides the details of the special manipulator functions used to perform
formatted IO in C++.
Function Description
setw(int) Used to set the width in number of characters for the immediate output data.
setfill(char) Used to fill the blank spaces in output with given character.
Function Description
The iomanip.h also contains the following format flags using in formatted IO in C++.
Flag Description
Lets look at the following code to illustrate the formatted IO operations using manipulators.
Explain
#include <iostream>
#include <fstream>
int main()
line();
line();
line();
line();
line();
line();
line();
return 0;
Output
To use the io manipulators the iomanip.h header file must be included.