0% found this document useful (0 votes)
27 views65 pages

C

C and C++ share similar syntax, code structure, and basic memory models, but C++ is a superset of C that introduces object-oriented programming features such as polymorphism, encapsulation, and inheritance. C is primarily procedural, focusing on functions, while C++ supports both procedural and object-oriented paradigms. Understanding the differences between these languages is essential for selecting the appropriate one for programming projects.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views65 pages

C

C and C++ share similar syntax, code structure, and basic memory models, but C++ is a superset of C that introduces object-oriented programming features such as polymorphism, encapsulation, and inheritance. C is primarily procedural, focusing on functions, while C++ supports both procedural and object-oriented paradigms. Understanding the differences between these languages is essential for selecting the appropriate one for programming projects.

Uploaded by

suganya.cse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Similarities between C and C++ are:

 Both the languages have a similar syntax.

 Code structure of both the languages are same.

 The compilation of both the languages is similar.

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

 Basic memory model of both is very close to the hardware.

 Same notions of stack, heap, file-scope and static variables are present in both the
languages.

Differences between C and C++ are:


C++ is often viewed as a superset of C. C++ is also known as a “C with class” This was very nearly
true when C++ was originally created, but the two languages have evolved over time with C picking
up a number of features that either weren’t found in the contemporary version of C++ or still
haven’t made it into any version of C++. That said, C++ is still mostly a superset of C adding Object-
Oriented Programming, Exception Handling, Templating, and a more extensive standard library.

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.

C does no support polymorphism, C++ supports polymorphism, encapsulation,


encapsulation, and inheritance which means and inheritance because it is an object
that C does not support object oriented oriented programming language.
C C++

programming.

C is (mostly) a subset of C++. C++ is (mostly) a superset of C.

Number of keywords in C: Number of keywords in C++:


* C90: 32 * C++98: 63
* C99: 37 * C++11: 73
* C11: 44 * C++17: 73
* C23: 59 * C++20: 81

C++ is known as hybrid language because C++


For the development of code, C
supports both procedural and object oriented
supports procedural programming.
programming paradigms.

Data and functions are separated in C


Data and functions are encapsulated together
because it is a procedural programming
in form of an object in C++.
language.

Data is hidden by the Encapsulation to ensure


C does not support information hiding. that data structures and operators are used as
intended.

Built-in & user-defined data types is supported


Built-in data types is supported in C.
in C++.

C is a function driven language because C is a C++ is an object driven language because it is


procedural programming language. an object oriented programming.

Function and operator overloading is not Function and operator overloading is


supported in C. supported by C++.

C is a function-driven language. C++ is an object-driven language


C C++

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.

Standard IO header is stdio.h. Standard IO header is iostream.h.

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 does not support inheritance. C++ supports inheritance.

Instead of focusing on data, C focuses on C++ focuses on data instead of focusing on


method or process. method or procedure.

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.

Direct support for exception handling is not


Exception handling is supported by C++.
supported by C.

scanf() and printf() functions are used for


cin and cout are used for input/output in C++.
input/output in C.

C structures don’t have access modifiers. C ++ structures have access modifiers.

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

result in many warnings and errors under C++


compiler.

C does not support overloading C++ does support overloading

Type punning with unions is undefined


Type punning with unions is allows (C99 and
behavior (except in very specific
later)
circumstances)

Named initializers must match the data layout


Named initializers may appear out of order
of the struct

File extension is “.cpp” or “.c++” or “.cc” or


File extension is “.c”
“.cxx”

Meta-programming: templates (macros are


Meta-programming: macros + _Generic()
still supported but discouraged)

There are 32 keywords in the C There are 97 keywords in the C++

C++ is a general-purpose and multi-paradigm computer programming language. The C++


programming language was created by Bjarne Stroustrup in the year 1983, at Bell Laboratories,
USA.

C++ is a general-purpose and multi-paradigm computer programming language. The C++


programming language supports both object-oriented programming and generic programming. C++
is an object-oriented programming language but it is not purely object-oriented programming
language because of features like friend functions, virtual functions, and virtual base classes.

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.

The programming paradigm is the way of writing computer programs. There are four programming
paradigms and they are as follows.

 Monolithic programming paradigm

 Structured-oriented programming paradigm

 Procedural-oriented programming paradigm

 Object-oriented programming paradigm

Monolithic Programming Paradigm

The Monolithic programming paradigm is the oldest. It has the following characteristics. It is also
known as the imperative programming paradigm.

 In this programming paradigm, the whole program is written in a single block.

 We use the goto statement to jump from one statement to another statement.

 It uses all data as global data which leads to data insecurity.

 There are no flow control statements like if, switch, for, and while statements in this
paradigm.

 There is no concept of data types.

An example of a Monolithic programming paradigm is Assembly language.

Structured-oriented Programming Paradigm

The Structure-oriented programming paradigm is the advanced paradigm of the monolithic


paradigm. It has the following characteristics.

 This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.
 It provides the concept of code reusability.

 It is introduced with the concept of data types.

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

Examples of a structured-oriented programming paradigm is ALGOL, Pascal, PL/I and Ada.

Procedural-oriented Programming Paradigm

The procedure-oriented programming paradigm is the advanced paradigm of a structure-oriented


paradigm. It has the following characteristics.

 This paradigm introduces a modular programming concept where a larger program is divided
into smaller modules.

 It provides the concept of code reusability.

 It is introduced with the concept of data types.

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

Examples of procedure-oriented programming paradigm is C, Visual Basic, FORTRAN, etc.

Object-oriented Programming Paradigm

The object-oriented programming paradigm is the most popular. It has the following characteristics.

 In this paradigm, the whole program is created on the concept of objects.

 In this paradigm, objects may communicate with each other through function.

 This paradigm mainly focuses on data rather than functionality.

 In this paradigm, programs are divided into what are known as objects.

 It follows the bottom-up flow of execution.

 It introduces concepts like data abstraction, inheritance, and overloading of functions and
operators overloading.

 In this paradigm, data is hidden and cannot be accessed by an external function.

 It has the concept of friend functions and virtual functions.

 In this paradigm, everything belongs to objects.

Examples of procedure-oriented programming paradigm is C++, Java, C#, Python, etc


Both object-oriented and procedure-oriented paradigms are very popular and most commonly used
programming paradigms. The following table gives the differences between those.

Procedure-oriented Object-oriented

It is often known as POP (procedure-oriented It is often known as OOP (object-oriented


programming). programming).

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.

It doesn’t support data abstraction. It supports data abstraction using access


specifiers that are public, protected, and
private.

It doesn’t support inheritance. It supports the inheritance of four types.

Overloading is not supported. It supports the overloading of function and


also the operator.

There is no concept of friend function and virtual It has the concept of friend function and
functions. virtual functions.

Examples - C, FORTRAN Examples - C++ , Java , VB.net, C#.net,


Python, R Programming, etc.

BASIC COMPONENTS OF C++:

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.

C++ Program Structure

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.

 Procedure-Oriented Programming Structure

 Object-Oriented Programming Structure

POP structure of C++ program

We use the following general structure to write C++ programs using Procedure-Oriented
Programming Paradigm.

General Structure of C++ Program (POP)

Explain

/*documentation*/

pre-processing statements

global declaration;

void main()

Local declaration;

Executable statements;

User defined functions

function body

Let's create a C++ program using the POP structure.

C++ Program to perform addition of two numbers using POP structure

Explain

#include < iostream.h >


int a, b;

void main()

int c;

void get_data();

int sum(int, int);

get_data();

c = sum(a, b);

cout << "Sum = " << endl;

void get_data()

cout << "Enter any two numbers: ";

cin >> a >> b;

int sum(int a, int b)

return a + b;

OOP structure of C++ program

We use the following general structure to write C++ programs using Object-Oriented Programming
Paradigm.

General Structure of C++ Program (OOP)

Explain

/*documentation*/

pre processing statements

class ClassName

{
member variable declaration;

member functions(){

function body

};

void main ()

ClassName object;

object.member;

Let's create a C++ program using the OOP structure.

C++ Program to perform addition of two numbers using OOP structure

Explain

#include < iostream.h >

class Addition{

int a, b;

public:

get_data(){

cout << "Enter any two numbers: ";

cin >> a >> b;

int sum(){

get_data();

return a + b;

}
};

void main(){

Addition obj;

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

 The POP structure program follows the top-bottom flow of execution.

 The OOP structure program follows the bottom-top flow of execution.

C++ Data Types

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.

 The type of value can be stored in a variable.

 The amount of memory in bytes has to be allocated for a variable.

 The range of values has to be stored in a variable.

The C++ programming language supports the following data types.

 Integer Data type

 Floating-point Data type

 Double Data type

 Character Data type

 Boolean Data type

 Void Data type

 Wide Character Data type

Integer Data type

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.

 Integer data type is represented using the keyword “int”.

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

 Floating-point data type is represented using the keyword “float”.

 The floating-point value is represented using the type specifier “%f”.

 The floating-point data type allows storing any value in the range from 2-31 to 231.

 The floating-point data type does not allows type modifier.

 The floating-point data type allows upto 6 decimal points.

Double Data type

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 is represented using the keyword “double”.

 The double value is represented using the type specifier “%ld”.

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

Character Data type

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 data type is represented using the keyword “char”.

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

Boolean Data type

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 boolean data type is represented using the keyword “bool”.

 The boolean value is represented using the type specifier “%d”.

 The boolean data type allows storing only 0 and 1.


 The boolean data type does not allows type modifier.

Void Data type

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 is represented using the keyword “void”.

 The void value does not have any type specifier.

 The void data type does not allows storing any value.

 The void data type does not allows type modifier.

Wide character Data type

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.

Data type Keyword Type specifier Memory size Range

Short Integer short int %d or %i 2 bytes -32768 to +32767

Long Integer long int or int %d or %i 4 bytes 2-31 to 231

Signed Integer int or short int or long int %d or %i 2 or 4 bytes -32768 to +32767 or 2-31 to 231

Unsigned Integer unsigned int %u 2 or 4 bytes 0 to +65535 or 0 to 232-1

Floating-point float %f 4 bytes +/- 3.4e +/- 38 (~7 digits)

Double double or long double %ld 8 bytes +/- 1.7e +/- 308 (~15 digits)

Signed Character char or signed char %c or %s 1 bytes -128 to +127

Unsigned Character unsigned char %c or %s 1 bytes 0 to +255

Boolean bool %d or none 1 bit 0 or 1

Void void none No memory No value


Data type Keyword Type specifier Memory size Range

Wide Character wchar_t %c or %s 2 bytes 2-15 to 215

Writing the C++ Program

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.

Example of a simple C++ program:

cpp

#include <iostream>

int main() {

std::cout << "Hello, World!" << std::endl;

return 0;

Compiling the Program

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.

Executing the Program

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

o On macOS and Linux:

sh

./hello
If everything is set up correctly, you should see the output:

Hello, World!

Using an Integrated Development Environment (IDE)

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

Variable is a value holder in the computer program.

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 has a name (user-specified) and an address.

 Every variable must be created with a data type.

 Every variable is allocated with a memory based on the data type of it.

 Every variable has a value.

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.

Syntax for creating a variable

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.

Syntax for creating a variable with initial value

data_type variable_name = value;

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.

Example statements for variables creation in c++

int a, b, c;

float x = 10.5, y;

char p = 'A', q = 'B', r = 'C';

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.

Consider the following example of C++ program.

C++ Program to illustrate local variables concept

Explain

#include < iostream.h >

using namespace std;

int sum(){

int a = 10, b = 20;

//cout<< "Result = " << result; // Error - result can't be accessed

return a + b;

int main()

int result;
result = sum();

cout << "Sum = " << result << endl;

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

Consider the following example of C++ program.

C++ Program to illustrate global variables concept

Explain

#include <iostream>

using namespace std;

int a = 10; // Global variable

int main()

int b = 20; // Local variable

void show();

cout << "Inside the main!!!" << endl;

cout << "a = " << a << endl;

show();

return 0;
}

void show(){

int a = 30; // Local variable with same name as global

cout << "Inside the show!!" << endl;

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.

Consider the following example of C++ program.

C++ Program to illustrate formal variables concept

Explain

#include <iostream>

using namespace std;

void add(int x, int y){

cout << "sum = " << x+y << endl;

int main()

int a = 10, b = 20; // Local variable

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.

Consider the following example of C++ program.

C++ Program to illustrate member variables concept

Explain

#include <iostream>

using namespace std;

class Sample{

public:

int a, b;

void setData(){

cout << "Enter a and b values: ";

cin >> a >> b;

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.

Consider the following example of C++ program.

C++ Program to illustrate instance variables concept

Explain

#include <iostream>

using namespace std;

class Sample{

public:

int a, b;

void setData(){

cout << "Enter a and b values: ";

cin >> a >> b;

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 value in the computer program. In other words, an expression is collection of


operators and operands which produce a unique value as result.

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.

There are three types of expressions and they are as follows.

 Infix Expression

 Prefix Expression

 Postfix Expression

The most commanly used expression type is infix expression.

Infix Expression

In this type of expression the operator is between the operands.

Prefix Expression

In this type of expression the operator is in-front of the operands.

Postfix Expression

In this type of expression the operator is after the operands.

C++ Operators

PREVIOUS

NEXT

An expression is value in the computer program. In other words, an expression is collection of


operators and operands which produce a unique value as result.
The C++ programming language provides a wide range of operators to perform mathematical, logical,
and other operations. An operator is a symbol used to perform mathematical and logical operations.
Every operator has a pre-defined functionality. However, C++ language provides a concept operator
overloading to assign user-defined functionality to most of the operators.

In C++ language, the operators are classified as follows.

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Increment and Decrement Operators

 Assignment Operators

 Bitwise Operators

 Conditional Operators

 Scope Resolution Operators

 Other Operators

Arithmetic 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.

Operator Meaning Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the Division 5%2=1

 The formal variables are allowed only when the function has parameters.

 The remainder of the division operator is used with integer data type only.

Relational Operators (<, >, <=, >=, ==, !=)

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

Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

Operator Meaning Example

&& 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.

Increment & Decrement Operators (++ & --)

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.

Operator Meaning Example

++ Increment - Adds one to existing value int a = 5;


Operator Meaning Example

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>

using namespace std;

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>

using namespace std;

int main()

int i = 5, j;

j = i++; // Post-Increment

cout << "i = " << i << ", j = " << j << endl;

return 0;

Output

Assignment Operators (=, +=, -=, *=, /=, %=)

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.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15


Operator Meaning Example

⇒ 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

Bitwise Operators (&, |, ^, ~, >>, <<)

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).

Operator Meaning Example

⇒ 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

Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first we verify a condition, then we perform
one operation out of the two operations based on the condition result. If the condition is TRUE the
first option is performed, if the condition is FALSE the second option is performed. The conditional
operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example code

A = (10<15)? 100 : 200; // ⇒ A value is 100

Scope Resolution Operator (: :)

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.

Special Operators (sizeof, pointer, comma, dot, etc.)

The following are the special operators in c programming language.

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

sizeof(A); // ⇒ the result is 2 if A is an integer

Pointer operator (*)

This operator is used to define pointer variables in c programming language.

Comma operator (,)

This operator is used to separate variables while they are declaring, separate the expressions in
function calls, etc.

Dot operator (.)

This operator is used to access members of a class, and structure.


The operators are also classified based on the number of operands required by the operator.

 Unary Operators

- Requires only one operand like ++ and --.

 Binary Operators

- Requires two operands like +, *, ==, ||, >>, etc.

 Ternary Operators

- Requires three operands like conditional operator.

C++ Expression Evaluation

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.

1. Pre-increment (or) pre- decrement

2. Peranthasis , shifting operators , sizeof

3. Astrick (*) , multiplication and division


4. Addition , substraction

5. Relational operators

6. Assignment operators

7. Post increment/post decrement

C++ Type Conversion

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.

 Implicit Conversion (Type Conversion)

 Explicit Conversion (Type Casting)

Implicit Conversion (Type Conversion)

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' ;

i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i

x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x

i = ch ; =======> Here the ASCII value of A (65) is assigned to i

Example code

Explain

#include <iostream>

using namespace std;


int main()

int i = 95 ;

float f = 90.99 ;

char ch = 'A' ;

i=f; //float to int --> 90.99 to 90

cout << "i value is " << i << endl;

f=i; // int to float --> 90 to 90.000000

cout << "f value is " << f << endl;

i = ch ; // char to int --> 'A' to 65

cout << "i value is " << i << endl;

return 0;

Explicit Conversion (Type Casting)

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

int totalMarks = 450, maxMarks = 600 ;


float average ;

average = (float) totalMarks / maxMarks * 100 ;

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>

using namespace std;

int main()

int a, b, c ;

float avg ;

cout << "Enter any three integer values : ";

cin >> a >> b >> c;

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

Pointer is a special variable used to store address of another variable.

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>

using namespace std;

int main()

int marks = 80;

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.

How to create a pointer in C++?

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;

A variable declaration prefixed with * symbol becomes a pointer variable.

Example

int *ptr;

In the above example declaration, the variable "ptr" is a pointer variable that holds any integer
variable address.

How to use a pointer?

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>

using namespace std;

int main()

int marks = 80, *ptr;

ptr = &marks; //Assigning address to pointer

cout << "Address of marks -> " << ptr << endl;
cout << "Value of marks -> " << *ptr << endl;

return 0;

Output

Pointer Memory Allocation

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>

using namespace std;

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>

using namespace std;

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.

How to create an array in C++?

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

data_type arrayName[size] = {value1, value2, value3,...};

or

data_type arrayName[] = {value1, value2, value3,...};

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];

string colors[5] = {"Red", "Green", "Blue", "Yellow", "Orange"};

string mobiles[] = {"iPhone", "Samsung", "Vivo", "Nokia", "Oppo", "One Plus"};

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.

How to use individual elements of an array?

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>

using namespace std;

int main()

string colors[5] = {"Red", "Green", "Blue", "Yellow", "Orange"};

cout << "First element is " << colors[0] << endl; // Accessing the first element

colors[3] = "Pink"; // Value at index 3 (Yellow) changed to Pink

cout << "Value at index 3 is " << colors[3] << endl;

return 0;

Output

Looping through an array

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>

using namespace std;

int main()
{

string colors[5] = {"Red", "Green", "Blue", "Yellow", "Orange"};

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

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.

 The array elements stored in contiguous memory locations.

C++ Pointers and Arrays

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.

 An array name is a constant pointer.

 We can use the array name to access the address and value of all the elements of that array.

 Since array name is a constant pointer we can't modify its value.


Example code

Explain

#include <iostream>

using namespace std;

int main()

string colors[5] = {"Red", "Green", "Blue", "Yellow", "Orange"};

cout << "Base address is " << &colors[0] << endl;

cout << "Base address is " << colors << endl; // array name as pointer

cout << "colors[3] = " << *(colors+3) << endl; // Accessing value using pointer array

colors++; // Generates an error

return 0;

Output

In the above example, the array name colors can be used as follows.

Addresses

 colors equal to &colors[0]

 colors + 1 equal to &colors[1]

 colors + 2 equal to &colors[2]

 colors + 3 equal to &colors[3]


 colors + 4 equal to &colors[4]

Values

 *colors equal to colors[0]

 *(colors + 1) equal to colors[1]

 *(colors + 2) equal to colors[2]

 *(colors + 3) equal to colors[3]

 *(colors + 4) equal to colors[4]

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.

 String as character array

 String as object of string class

String as character array

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>

using namespace std;

int main()

char name[30] = {'R', 'a', 'm', 'a'}; // string as an array

cout << "Hello, " << name << endl;


return 0;

 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 size of the character array is fixed at compile time.

String as object of string class

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>

using namespace std;

int main()

string name = "Rama"; // string as an object

cout << "Hello, " << name << endl; // Accessing hole string

cout << name[2] << endl; // Accessing a character from string

name[2] = 'n'; // Changing a character at index 2

cout << "Hello, " << name << endl;

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.

 strcpy(string s1, string s2)


- Used to copy string s2 into string s1

 strcat(string s1, string s2)


- Used to perform the concatination of two strings

 strlen(string s)
- Used to find the length of a string (total number of characters)

 strchr(string s, char ch)


- Returns a pointer the first occurance of the given character in the string s.

 strstr(string s1, string s2)


- Returns a pointer the first occurance of the string s2 in the string s1.

 strcmp(string s1, string s2)


- Compares both string s1 and string s2 and returns 0 if both are the same; less than 0 if
s1<s2; greater than 0 if s1>s2.

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

using namespace std;

int main()

{
string name = "Rama"; // string as an object

string message = "Good Morning";

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

The if is a flow control statement used to make a decision based on a condition.

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) {

// block of code to be executed if the condition is true

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.

Example - Code to illustrate the if statement and condition

Explain

#include <iostream>

using namespace std;

int main()

int a = 10;

if(a < 100) {


cout << a << " is smaller than 100" << endl; // Executed

if(5) {

cout << "Value 5 is true" << endl; // Executed

if(0) {

cout << "Value 0 is false" << endl; // Not executed

if(a = 30) {

cout << "Value 30 is true" << endl; // Executed

if(a = 30, 0) {

cout << "Value 0 is false" << endl; // Not executed

if(a = 30, 0, 9) {

cout << "Value 9 is true" << endl; // Executed

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.

 Always else must follow the if statement.

 else can not be used allown, however if can be.

Syntax - if-else Statement

Explain

if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

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.

Example - Code to find largest of two numbers

Explain

#include <iostream>

using namespace std;


int main()

int a = 10, b = 30;

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.

Syntax - if-elseif Statement

Explain

if (condition_1) {

// block of code to be executed if the condition_1 is true

} else if (condition_2) {

// block of code to be executed if the condition_2 is true

The condition_2 is varified only when condition_1 is false.

Example - Code to find largest of three numbers

Explain

#include <iostream>
using namespace std;

int main()

int a = 10, b = 30, c = 20;

if(a > b && a > c) {

cout << a << " is larger than " << b << " and " << c << endl;

} else if( b > c) {

cout << b << " is larger than " << a << " and " << c << endl; // executed

} else {

cout << c << " is larger than " << a << " and " << b << endl;

return 0;

Output

 The if allows to define nested if statements. (if within another if)

C++ switch Statement

PREVIOUS

NEXT

The switch is a multi way selection statement.

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;

...

default: default block of code

Let's look at the following code.

Example - Code to illustrate the if statement and condition

Explain

#include <iostream>

using namespace std;

int main()

int key_value;

cout << endl << "Enter any digit: ";

cin >> key_value;

switch( key_value ) {

case 0: cout << "ZERO" << endl;

break ;

case 1: cout << "ONE" << endl;

break ;

case 2: cout << "TWO" << endl;

break ;

case 3: cout << "THREE" << endl;

break ;

case 4: cout << "FOUR" << endl;


break ;

case 5: cout << "FIVE" << endl;

break ;

case 6: cout << "SIX" << endl;

break ;

case 7: cout << "SEVEN" << endl;

break ;

case 8: cout << "EIGHT" << endl;

break ;

case 9: cout << "NINE" << endl;

break ;

default: cout << "Not a Digit" << endl;

return 0;

Output

When we use switch statement we must follow the following points.

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

 Duplicate case values are not allowed.

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

 Nesting of switch statements are allowed.

C++ Error Handling during File Operations

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 open a file for reading might not exist.

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

 When trying to operate on a file that has not been open.

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.

Flag Bit Meaning

badbit 1 when a fatal I/O error has occurred, 0 otherwise.

failbit 1 when a non-fatal I/O error has occurred, 0 otherwise

goodbit 1 when no error has occurred, 0 otherwise

eofbit 1 when end-of-file is encountered, 0 otherwise.

We use the above flag bits to handle the errors during the file operations.

Error Handling During the File Operations in C++

The C++ programming language provides several built-in functions to handle errors during file
operations. The file error handling

The following are the built-in functions to handle file errors.

Function Return Value

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.

Let's look at the following code.

Example - Code to illustrate the bad( ) function

Explain

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream file;

file.open("my_file.txt", ios::out);

string data;

file >> data;

if(!file.bad()){

cout << "Operation not success!!!" << endl;

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.

Let's look at the following code.

Example - Code to illustrate the fail( ) function

Explain

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream file;

file.open("my_file.txt", ios::out);

string data;

file >> data;

if(file.fail()){

cout << "Operation not success!!!" << endl;

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).

Let's look at the following code.

Example - Code to illustrate the eof( ) function

Explain

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream file;

file.open("my_file.txt", ios::in);

string data;

while(!file.eof()){

file >> data;

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).

Let's look at the following code.

Example - Code to illustrate the good( ) function

Explain

#include <iostream>

#include <fstream>

using namespace std;

int main()

fstream file;

file.open("my_file.txt", ios::in);

cout << "goodbit: " << file.good() << endl;

string data;

cout << endl << "Data read from file:" << endl;

while(!file.eof()){

file >> data;

cout << data << " ";


}

cout << endl;

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.

In C++, there are two ways to perform the formatted IO operations.

 Using the member functions of ios class.

 Using the special functions called manipulators defined in iomanip.h.

Formatted IO using ios class memebers

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.

unsetf(format flags) Used to clear the format flag setting.

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.

Example - Code to illustrate the formatted IO using ios class

Explain

#include <iostream>

#include <fstream>

using namespace std;

int main()

cout << "Example for formatted IO" << endl;

cout << "Default: " << endl;

cout << 123 << endl;

cout << "width(5): " << endl;

cout.width(5);

cout << 123 << endl;

cout << "width(5) and fill('*'): " << endl;

cout.width(5);

cout.fill('*');

cout << 123 << endl;


cout.precision(5);

cout << "precision(5) ---> " << 123.4567890 << endl;

cout << "precision(5) ---> " << 9.876543210 << endl;

cout << "setf(showpos): " << endl;

cout.setf(ios::showpos);

cout << 123 << endl;

cout << "unsetf(showpos): " << endl;

cout.unsetf(ios::showpos);

cout << 123 << endl;

return 0;

Output

Formatted IO using manipulators

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

setprecision(int) Used to set the number of digits of precision.

setbase(int) Used to set the number base.

setiosflags(format flags) Used to set the format flag.

resetiosflags(format flags) Used to clear the format flag.

The iomanip.h also contains the following format flags using in formatted IO in C++.

Flag Description

endl Used to move the cursor position to a newline.

ends Used to print a blank space (null character).

dec Used to set the decimal flag.

oct Used to set the octal flag.

hex Used to set the hexadecimal flag.

left Used to set the left alignment flag.

right Used to set the right alignment flag.

showbase Used to set the showbase flag.

noshowbase Used to set the noshowbase flag.

showpos Used to set the showpos flag.

noshowpos Used to set the noshowpos flag.

showpoit Used to set the showpoit flag.

noshowpoint Used to set the noshowpoint flag.

Lets look at the following code to illustrate the formatted IO operations using manipulators.

Example - Code to illustrate the formatted IO using manipulators

Explain

#include <iostream>

#include <fstream>

using namespace std;


void line() {

cout << "-------------------------------" << endl;

int main()

cout << "Example for formatted IO" << endl;

line();

cout << "setw(10): " << endl;

cout << setw(10) << 99 << endl;

line();

cout << "setw(10) and setfill('*'): " << endl;

cout << setw(10) << setfill('*') << 99 << endl;

line();

cout << "setprecision(5): " << endl;

cout << setprecision(5) << 123.4567890 << endl;

line();

cout << "showpos: " << endl;

cout << showpos << 999 << endl;

line();

cout << "hex: " << endl;

cout << hex << 100 << endl;

line();

cout << "hex and showbase: " << endl;

cout << showbase << hex << 100 << endl;

line();

return 0;

Output
 To use the io manipulators the iomanip.h header file must be included.

You might also like