C++ Notes For CS Engineers
C++ Notes For CS Engineers
Introduction to C++
What is programming?
Programming is an exercise or practice that boost our logical thinking and improves a problem-
solving skill. It teaches us how to accomplish a task with the help of a computer program or
software. Therefore, in simple terms, programming is a task to implement a solution to a problem
in the form of computer language. In this section, we will discuss the word programming,
programming languages, its type, advantages, disadvantages, and their uses.
Definition of Programming
In computer science fields, the word program characterizes what a computer actually does and
this process is known as programming.
We can also define the term programming as it is the process that models or structure the set of
instructions that instruct the machine how to perform a task and what to perform. It can be
done using a variety of programming languages such as C, C++, C#, Python, Java, etc.
Advantages of Programming
o It enhances problem-solving skills.
o Using programming, we can solve complex problems.
o It is also learning with fun.
o It can perform multiple tasks can be bundled into one module.
o It saves time and effort.
Disadvantages of Programming
o Knowledge of computer is mandatory.
o Logical thinking should be strong.
Programming Paradigms
In layman's terms, programming paradigms are a fundamental style of computer programming.
In technical terms, a programming paradigm is a way to deal with tackle issues utilizing some
programming language. Additionally, we can say that it is a strategy to take care of an issue using
tools and techniques that are accessible to us following some methodology.
It differs in the concepts and methods that are used to represent the elements (such as objects,
variables, functions, and constraints) of a program. And the steps that involve a calculation
(like assignations, evaluation, continuations, and data flows). The lowest programming
paradigm is machine code.
There are lots of things for programming languages that are known. However, every one of them
needs to follow some procedure when they are executed and this approach/methodology is a
paradigm.
Types of Programming Paradigms
There is the following two programming paradigm:
o Imperative Programming Paradigm
1
o Declarative Programming Paradigm
Object-oriented Programming
The object-oriented programming paradigm is based on the concept of object. An object
contains data in the form of fields that are known as attributes and the procedures are known
as methods.
Since objects work independently, they are encapsulated into modules. We can communicate with
an object by using message passing.
Object-oriented programming can be achieved by using programming languages such as Java,
C++, C#, PHP, and Python, etc.
2
Procedural Programming
The paradigm deals with procedure calls that are called routines or functions. the functions
contain a series of computational commands to be carried out to achieve a certain outcome.
It is just like a procedure, with a list of step-by-step instructions for the computer program to
follow. The code can easily be reused in different parts of the program. The advantage of the
paradigm is that the code can be easy to learn and read in simple programs. Though, while dealing
with a complex problem, we run the risk of ending up with a huge volume of code.
Example of procedural programming is BASIC, C, and Pascal.
Declarative programming is a style of building the structure and elements of computer programs.
It expresses the logic of a computation without describing its control flow. In other words, styles
of programming that are not imperative are called declarative programming paradigm. It
emphasizes what the program should accomplish.
Examples of declarative programming paradigm are Scala, Haskell, Erlang, Lisp, ML, Closure,
SQL, XSQL, etc.
Advantages
o Efficient and shortcode
o Referential Transparency
o Idempotence
o Error recovery
o Readability
o Commutativity
o Easy optimization
Disadvantages
o Difficult to understand.
o It is abed on an unfamiliar conceptual model.
o Difficult to accept characteristics of specific applications into account while programming.
Types of Declarative Programming Paradigms
o Functional Programming
o Logical Programming
o Database Processing Approach
3
Functional Programming
It is a subset of declarative programming. Programs that are written using the paradigm use
functions, blocks of codes, intended to behave like mathematical functions. It discourages
changes in the value of variables through the assignment. Instead makes a great deal with
recursion.
Examples of functional programming Haskell, SML, Clojure, Scala, Erlang, Clean, F#, etc.
Logical Programming
The Logical Paradigm adopts a decisive strategy to critical thinking. Different consistent
declarations about a circumstance are made, setting up totally known realities. The paradigm is
divided into three sections:
1. A series of definitions/affirmations that characterize the problem domain
2. Statements of facts that are relevant
3. Statement of objectives or goals in the form of query
Example of logical programming is PROLOG, SQL, etc.
Multi-Paradigm
The programming languages that support more than one programming paradigm fall into this
category. The design goal of such languages is to allow programmers to use the most suitable
programming style associated with languages constructs for a given job.
The example of multi-paradigm programming languages is C++, Java, Python, etc. The
languages support object-oriented programming greater or lesser degree, typically in
combination with imperative and declarative programming paradigm.
Usually, in a program, distinctive programming standards are utilized. Henceforth, programming
dialects offer help (with various degrees) for the different standards.
The following table provides a brief description of programming paradigms.
4
Paradigms Key Concept Program Program Execution Result
Procedural Command Sequence of Execution of Final state of
commands commands computer memory
Functional Function Collections of Executions of Value of the main
functions functions function
Logic Predicate Logic formulas: Logic proving of the Failure of success of
axioms and a theorem proving
theorem
Object- Object Collections of Exchange of messages Final state of the
oriented classes of objects between the objects object's state
The object-oriented paradigms state is the most abstract, as it's basic ideas can be easily
combined with the principles and programming techniques of the other styles.
Programming Paradigm Programming Languages
Procedural FORTRAN, COBOL, ALGOL, BASIC, C, and Pascal.
Functional Haskell, SML, Clojure, Scala, Erlang, Clean, F#, etc.
Object-oriented Java, Python, C++, C#, Kotlin, Scala, Swift, Ruby,
Perl, etc.
Logical PROLOG, SQL, etc.
Parallel Processing SISAL, Parallel Haskell, SequenceL, System C (for
FPGAs), Mitrion-C, VHDL, and Verilog, MPI.
Database Processing Approach SQL (only DQL), QML, RDQL, and SPARQL.
5
Decision The user makes decisions and instructs the It allows the compiler to
Capability compiler. make decisions.
Humans need to be able to control the interaction between people and machines. Since
computers and machines are able to do things so efficiently and accurately, we use computer
programming to harness that computing power.
Therefore, programming is used for solving complex problems. It makes our task easy, and also
saves time and effort.
Programming Process
Programming includes the different phases. It works on the edit-compile-verify approach. The
following figure demonstrates the same.
6
Programming Vs. Coding
In the computer science field, there are two buzzwords i.e., coding and programming. On
hearing these two words sound similar but both are different words. These two words are used
interchangeably.
Contrary, there are some differences between programming and coding as per the software
development vocabulary.
Programming
It is the process of developing a fully functional, error-free software program. It includes the
following:
7
o Planning
o Designing
o Testing
o Deploying
o Maintenance
We can say that programming is not only limited to coding. It also implements algorithms, data
structures, and mitigating issues, and much more.
Coding
Coding is an act of interpreting codes from human language to machine-based language. We can
also say that it is a subset of programming that gives foundation to programming. In coding, the
programmer instructs the computer, what to perform.
The key difference between programming and coding is that programming is the process of
developing a program or application that trails certain standards and performs a specified task.
Skill Required One must friendly with data structure, One must friendly with any
algorithm, and analytical skills. programming language such as Java,
C, C++, etc.
Tools Required Tools for analysis, code generator, It requires only text-editors such
database, data structure, testing as WordPad or Notepad, IDE such as
frameworks, linkers, compilers, code Eclipse, Bootstrap are required in
editors, GUI designers, assemblers, coding.
debuggers, and performance analysis
tools are required in programming.
8
Viewpoint An orderly approach and attention to Trial and error approach with no
minute details. previous preparations.
Outcome We get a well-designed software, We get a fully functional small piece
application, or website. of code.
Expertise While dealing with programming one In coding, one must have knowledge
must have experienced in creating of programming language, syntax
algorithms, modeling problems, related to language, keywords, etc.
processing data.
Programming paradigms
A programming paradigm is a model of programming based on distinct concepts that shapes
the way programmers design, organize and write programs. A multi-paradigm programming
language allows programmers to choose a specific single approach or mix parts of different
programming paradigms. C++ as a multi-paradigm programming language supports single or
mixed approaches using Procedural or Object-oriented programming and mixing in utilization of
Generic and even Functional programming concepts.
Procedural programming
Procedural programming can be defined as a subtype of imperative programming as a
programming paradigm based upon the concept of procedure calls, in which statements are
structured into procedures (also known as subroutines or functions). Procedure calls are modular
and are bound by scope. A procedural program is composed of one or more modules. Each
module is composed of one or more subprograms. Modules may consist of procedures, functions,
subroutines or methods, depending on the programming language. Procedural programs may
possibly have multiple levels or scopes, with subprograms defined inside other subprograms. Each
scope can contain names which cannot be seen in outer scopes.
Procedural programming offers many benefits over simple sequential programming since
procedural code:
is easier to read and more maintainable
is more flexible
facilitates the practice of good program design
allows modules to be used again in the form of code libraries.
Note:
Nowadays it is very rare to see C++ strictly using the Procedural Programming paradigm, mostly it
is used only on small demonstration or test programs.
Typing refers to how a computer language handles its variables, how they are differentiated
by type. Variables are values that the program uses during execution. These values can change;
9
they are variable, hence their name. Static typing usually results in compiled code that executes
more quickly. When the compiler knows the exact types that are in use, it can produce machine
code that does the right thing easier. In C++, variables need to be defined before they are used
so that compilers know what type they are, and hence is statically typed. Languages that are not
statically typed are called dynamically typed.
Static typing usually finds type errors more reliably at compile time, increasing the reliability of
compiled programs. Simply put, it means that "A round peg won't fit in a square hole", so the
compiler will report it when a type leads to ambiguity or incompatible usage. However,
programmers disagree over how common type errors are and what proportion of bugs that are
written would be caught by static typing. Static typing advocates believe programs are more
reliable when they have been type checked, while dynamic typing advocates point to dynamic
code that has proved reliable and to small bug databases. The value of static typing, then,
presumably increases as the strength of the type system is increased.
A statically typed system constrains the use of powerful language constructs more than it
constrains less powerful ones. This makes powerful constructs harder to use, and thus places the
burden of choosing the "right tool for the problem" on the shoulders of the programmer, who
might otherwise be inclined to use the most powerful tool available. Choosing overly powerful
tools may cause additional performance, reliability or correctness problems, because there
are theoretical limits on the properties that can be expected from powerful language constructs.
For example, indiscriminate use of recursion or global variables may cause well-documented
adverse effects.
Static typing allows construction of libraries which are less likely to be accidentally misused by
their users. This can be used as an additional mechanism for communicating the intentions of the
library developer.
Type checking
Process of verifying and enforcing the constraints of types, which can occur at either compile-time
or run-time. Compile time checking, also called static type checking, is carried out by the compiler
when a program is compiled. Run time checking, also called dynamic type checking, is carried out
by the program as it is running. A programming language is said to be strongly typed if the type
system ensures that conversions between types must be either valid or result in an error. A weakly
typed language on the other hand makes no such guarantees and generally allows automatic
conversions between types which may have no useful purpose. C++ falls somewhere in the
middle, allowing a mix of automatic type conversion and programmer defined conversions,
allowing for almost complete flexibility in interpreting one type as being of another type.
Converting variables or expression of one type into another type is called type casting.
10
Object-oriented programming
Object-oriented programming can be seen as an extension of procedural programming in
which programs are made up of collections of individual units called objects that have a distinct
purpose and function with limited or no dependencies on implementation. For example, a car is
like an object; it gets you from point A to point B with no need to know what type of engine the
car uses or how the engine works. Object-oriented languages usually provide a means
of documenting what an object can and cannot do, like instructions for driving a car.
What is C++
C++ is a general purpose, case-sensitive, free-form programming language that supports object-
oriented, procedural and generic programming.
C++ is a middle-level language, as it encapsulates both high and low level language features.
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
o The core library includes the data types, variables and literals, etc.
o The standard library includes the set of functions manipulating strings, files, etc.
o The Standard Template Library (STL) includes the set of methods manipulating a data
structure.
Usage of C++
By the help of C++ programming language, we can develop different types of secured and robust
applications:
o Window application
o Client-Server application
o Device drivers
o Embedded firmware etc
11
C++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily change the
C++ program code.
File: main.cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello C++ Programming";
return 0;
}
2) Data is less secured in C. In C++, you can use modifiers for class members
to make it inaccessible for outside users.
5) In C, you can't use functions in structure. In C++, you can use functions in structure.
7) In C, scanf() and printf() are mainly used for C++ mainly uses stream cin and cout to
input/output. perform input and output operations.
9) C programs are divided into procedures and C++ programs are divided into functions and
modules classes.
10) C does not provide the feature of namespace. C++ supports the feature of namespace.
12
11) Exception handling is not easy in C. It has to C++ provides exception handling using Try and
perform using other functions. Catch block.
C++ history
History of C++ language is interesting to know. Here we are going
to discuss brief history of C++ language.
Let's see the programming languages that were developed before C++ language.
C++ Features
C++ is a widely used programming language.
13
It provides a lot of features that are given below.
1. Simple
2. Abstract Data types
3. Machine Independent or Portable
4. Mid-level programming language
5. Structured programming language
6. Rich Library
7. Memory Management
8. Quicker Compilation
9. Pointers
10. Recursion
11. Extensible
12. Object-Oriented
13. Compiler based
14. Reusability
15. National Standards
16. Errors are easily detected
17. Power and Flexibility
18. Strongly typed language
19. Redefine Existing Operators
20. Modeling Real-World Problems
14
21. Clarity
For example, a sports car is an object. Some of its members might be its height, weight,
acceleration, and speed. An object's members just hold data about that object. Some of the
methods of the sports car could be "drive", "park", "race", etc. The methods really do not mean
much unless associated with the sports car, and the same goes for the members.
The "blueprint" that lets us build our sports car object is called a class. A class does not tell us
how fast our sports car goes, or what color it is, but it does tell us that our sports car will have a
member representing speed and color, and that they will be say, a number and a word,
respectively. The class also lays out the methods for us, telling the car how to park and drive, but
these methods can not take any action with just the blueprint - they need an object to have an
effect.
Class in C++ is the same as structure in C; The difference is that class users can hide data through
the private option. In C++, an object is an instance of a class which is treated like a built-in variable
which holds many values.
Object-Oriented Programming
The word object-oriented is the combination of two words i.e. object and oriented. The
dictionary meaning of the object is an article or entity that exists in the real world. The meaning
of oriented is interested in a particular kind of thing or entity. In layman's terms, it is a
programming pattern that rounds around an object or entity are called object-oriented
programming.
15
The object-oriented programming is basically a computer programming design philosophy or
methodology that organizes/ models software design around data, or objects rather than
functions and logic.
An object is referred to as a data field that has unique attributes and behavior. Everything in OOP
is grouped as self-sustainable objects.
It is the most popular programming model among developers. It is well suited for programs that
are large, complex, and actively updated or maintained. It simplifies software development and
maintenance by providing major concepts such as abstraction, inheritance, polymorphism,
and encapsulation. These core concepts support OOP.
A real-world example of OOP is the automobile. It more completely illustrates the power of object-
oriented design.
Points to Remember
o Everything is an object
o Developer manipulates objects that uses message passing.
o Every object is an instance of a class.
o The class contains the attribute and behavior associated with an object.
Pillars of OOPs
The major concepts that we have discussed above are known as pillars of OOPs. There
are four pillars on which OOP rests.
o Abstraction
o Encapsulation
o Inheritance
o Polymorphism
Abstraction
The concept allows us to
hide the implementation
from the user but shows
only essential information to
the user. Using the concept
developer can easily make
changes and added over
time.
16
There are the following advantages of abstraction:
o It reduces complexity.
o It avoids delicacy.
o Eases the burden of maintenance
o Increase security and confidentially.
Encapsulation
Encapsulation is a mechanism that allows us to bind data and functions of a class into an entity.
It protects data and functions from outside interference and misuse. Therefore, it also provides
security. A class is the best example of encapsulation.
Inheritance
The concept allows us to inherit or acquire the properties of an existing class (parent class) into a
newly created class (child class). It is known as inheritance. It provides code reusability.
17
Polymorphism
The word polymorphism is derived from the two words i.e. ploy and morphs. Poly means many
and morphs means forms. It allows us to create methods with the same name but different
method signatures. It allows the developer to create clean, sensible, readable, and resilient code.
The above figure best describes the concepts of polymorphism. A person plays an employee role
in the office, father and husband role in the home.
OOPs Concepts
The OOPs concepts include the following:
1. Object
2. Class
3. Inheritance
18
4. Polymorphism
5. Abstraction
6. Encapsulation
Object
An object is a real-world entity that has attributes, behavior, and properties. It is referred to as an
instance of the class. It contains member functions, variables that we have defined in the class. It
occupies space in the memory. Different objects have different states or attributes, and behaviors.
Class
A class is a blueprint or template of an object. It is a user-defined data type. Inside a class, we
define variables, constants, member functions, and other functionality. it binds data and functions
together in a single unit. It does not consume memory at run time. Note that classes are not
considered as a data structure. It is a logical entity. It is the best example of data binding. Note
that a class can exist without an object but vice-versa is not possible.
19
The following figure best illustrates the class and object in OOP.
Apart from these core concepts, there are some other object-oriented concepts used in OOP.
Coupling
In programming, separation of concerns is known as coupling. It means that an object cannot
directly change or modify the state or behavior of other objects. It defines how closely two objects
are connected together. There are two types of coupling, loose coupling, and tight coupling.
Objects that are independent of one another and do not directly modify the state of other objects
is called loosely coupled. Loose coupling makes the code more flexible, changeable, and easier to
work with.
Objects that depend on other objects and can modify the states of other objects are called tightly
coupled. It creates conditions where modifying the code of one object also requires changing the
code of other objects. The reuse of code is difficult in tight coupling because we cannot separate
the code.
Cohesion
In OOP, cohesion refers to the degree to which the elements inside a module belong together. It
measures the strength of the relationship between the module and data. In short, cohesion
represents the clarity of the responsibilities of a module. It is often contrasted with coupling.
It focuses on a how single module or class is intended. Higher the cohesiveness of the module or
class, better is the object-oriented design.
20
There are two types of cohesion, i.e. High and Low.
Composition
Composition is one of the vital concepts in OOP. It describes a class that references one or more
objects of other classes in instance variables. It allows us to model a has-a association between
objects. We can find such relationships in the real world. For example, a car has an engine. the
following figure depicts the same
Association
The association defines the relationship between the objects. Note that an object can be
associated with one or more than one object. The relationship can be unidirectional or
bidirectional. There are the following types of association.
o One to One
o One to Many
21
o Many to One, and
o Many to Many
Aggregation
It is an advanced form of association in which each object has its own Lifecycle but there exists
ownership as well. In other words, a relationship where a child can exist independently of the
parent. It is also termed as has-a relationship in Java. Like, inheritance represents the is-a
relationship. It is another way to reuse objects.
Where it is used?
OOP is often the best use when we are dealing with manufacturing and designing applications. It
provides modularity in programming. It allows us to break down the software into chunks of small
problems that we then can solve one object at a time.
It should be used where the reusability of code and maintenance is a major concern. Because it
makes development easy and we can easily append code without affecting other code blocks. It
should be used where complex programming is a challenge.
22
Benefits of OOP
o Modular, scalable, extensible, reusable, and maintainable.
o It models the complex problem in a simple structure.
o Object can be used across the program.
o Code can be reused.
o We can easily modify, append code without affecting the other code blocs.
o Provides security through encapsulation and data hiding features.
o Beneficial to collaborative development in which a large project is divided into groups.
o Debugging is easy.
Limitations of OOP
o Requires intensive testing processes.
o Solving problems takes more time as compared to Procedure Oriented Programming.
o The size of the programs created using this approach may become larger than the
programs written using the procedure-oriented programming approach.
o Software developed using this approach requires a substantial amount of pre-work and
planning.
o OOP code is difficult to understand if you do not have the corresponding class
documentation.
o In certain scenarios, these programs can consume a large amount of memory.
o Not suitable for small problems.
o Takes more time to solve problems.
Applications of OOPs
o Computer graphics applications
o Object-oriented database
o User-interface design such as windows
o Real-time systems
o Simulation and modeling
o Client-Server System
o Artificial Intelligence System
o CAD/CAM Software
o Office automation system
23
C++ Basic Input and Output (I/O)
C++ I/O operation uses the stream concept. The series of bytes or flow of data is referred to as a
stream. It accelerates performance.
If bytes are transferred from main memory to a device like a printer, display screen, network
connection, etc. this is called an output operation.
An input operation occurs when bytes flow from a device such as a printer, display screen, or
network connection to main memory.
In C++, predefined functions and declarations are provided through header files, allowing you
to do specific tasks without having to write new code from the start. A few important header files
for input/output operations in C++ include functions for effectively carrying out input and output
tasks. The C++ Standard Library, a collection of classes and methods created in the C++
programming language, contains these header files. Let us discuss the main header files for
input/output operations:
<iostream> It is used to define the cout, cin and cerr objects, which correspond to
standard output stream, standard input stream and standard error stream,
respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such
as setprecision and setw.
iostream: It is one of the most important header files for input/output operations in C++. It stands
for "input-output" stream. For working with various forms of input/output streams,
the iostream header file includes the classes istream (input stream) and ostream (output
stream) as well as its derived classes ifstream, ofstream, and stringstream. This header file's
most typically used classes are cin (standard input) and cout (standard output), which allow
you to read user input and display output to the console.
iomanip: This header file stands for "input-output manipulation". It provides tools to
format input and output. It allows you to modify the alignment, width, precision, and other
formatting features of the input and output. Setw, setprecision, fixed, left, right, and other
regularly used functions are listed below. It is especially handy for presenting data in a certain
way.
24
Example:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159;
cout << fixed << setprecision(2) << "Value of pi: " << pi << endl;
return 0;
}
fstream: The header file for file input/output operations is called fstream. It comprises classes for
reading from and writing to files ifstream (input file stream) and ofstream (output file
stream). The system uses these classes to open read-only and write-only files.
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("output.txt");
if (outputFile.is_open()) {
outputFile << "Hello, File I/O!";
outputFile.close();
cout << "File is written successfully." << endl;
} else {
cout << "Failed to open the file." << endl;
}
return 0;
}
Output
25
In C++, we frequently use 'using namespace std;' after the header files. The namespace
std; statement is frequently used in C++ to streamline the code when working with standard
library components. Let's examine this statement's function and application in more detail:
The term "standard" is shortened to "std", and all elements of the standard library are contained
within it. By doing this, name conflicts with identifiers set up in your code are reduced.
int main() {
cout << "Hello, world!" << endl;
return 0;
}
26
Un-buffered standard error stream (cerr):
cerr stands for "standard error".
It is an unbuffered stream, meaning that output sent to cerr is immediately displayed on the
console without buffering.
It is typically used for displaying error messages and diagnostic information, which need to be
displayed immediately to avoid delays caused by buffering.
int main() {
std::cerr << "This is an error message." << std::endl;
return 0;
}
Advantages of OOP
Let us now look at the various OOPS advantages.
Modularity: OOP divides complex systems into smaller components, making the
codebase easier to comprehend, create, and maintain.
Reusability: Inheritance allows code reuse, improving code quality and saving time.
Encapsulation: Protects data integrity and privacy by restricting direct access and allowing
controlled access through methods.
Flexibility and Scalability: OOP enables easy addition and modification of features
without impacting the entire codebase.
Code Organization: OOP promotes a structured approach, enhancing collaboration and
code readability.
Code Maintenance: Changes and bug fixes can be made to specific objects or classes
without affecting other parts of the system, reducing errors and improving debugging.
Code Reusability: OOP encourages the development of reusable code elements, saving
time and improving system reliability.
Better Problem Solving: OOP models real-world systems, allowing developers to create
intuitive solutions that closely mimic real-world circumstances.
Disadvantages of OOP
After learning about the OOPS advantages, let us now look at the various disadvantages of OOP.
Steeper learning curve: OOP introduces complex concepts like classes, objects,
inheritance, and polymorphism, making it harder for new programmers to grasp and apply
them effectively.
Increased complexity: OOP's emphasis on modularity and code organization can make
larger projects more challenging to understand and maintain.
27
Performance overhead: OOP languages often have a performance cost compared to
procedural languages due to the additional abstraction layers introduced by objects and
encapsulation.
Dependency management: Inheritance and code reuse in OOP can create
interdependencies among classes, making it difficult to manage changes and maintain
overall functionality.
Overuse of inheritance: Improper use of inheritance can lead to complex class hierarchies
and tightly coupled classes, making code maintenance and modifications more difficult in
the future.
C++ Variable
Variables are the fundamental building blocks of data manipulation and storage in programming,
acting as dynamic containers for data in the C++ programming language. A variable is more
than just a memory label. It serves as a link between abstract ideas and concrete data storage,
allowing programmers to deftly manipulate data.
With the help of C++ variables, developers may complete a wide range of jobs, from
simple arithmetic operations to complex algorithmic designs. These programmable containers
can take on a variety of shapes, such as integers, floating-point numbers, characters, and user-
defined structures, each of which has a distinctive impact on the operation of the program.
Programmers follow a set of guidelines when generating variables, creating names that combine
alphanumeric letters and underscores while avoiding reserved keywords. More than just
placeholders, variables are what drive user input, intermediary calculations, and the dynamic
interactions that shape the program environment.
A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.
Important Ideas: Programming is fundamentally based on C++ variables, which allow for
the storing, manipulation, and interaction of data inside a program.
Memory Storage: Variables are named memory regions that may hold values of different data
kinds, ranging from characters and integers to more intricate user-defined structures.
Dynamic character: Programming that is responsive and dynamic is made possible by the ability
to assign, modify, and reuse data through variables.
28
Data Types: The several data types that C++ provides, including int, float, char, and others,
each define the sort of value that a variable may store.
Variable declaration: Use the syntax type variable_name to define a variable, containing
its type and name.
Initialization: When a variable is declared, it can be given a value, such as int age = 25.
Rules and Naming: Variable names must begin with a letter or an underscore, avoid
reserved keywords, and be composed of letters, numbers, and underscores.
Scope: Variables have a scope that specifies the areas of a program where they may be accessed
and used.
Reusability and Modularity: Variables with appropriate names make code easier
to comprehend, encourage modularity, and allow for code reuse.
Memory Control: Incorrect usage of variables can result in memory leaks or inefficient allocation,
therefore understanding those helps with memory management.
Applications in the Real World: Variables are used in a variety of applications, including web
applications, system programming, and scientific simulations.
Debugging and upkeep: The proper use of variables reduces errors and enhances program
quality while making debugging and code maintenance easier.
Interactivity: Variables are essential for interactive programs to capture user input and enable
dynamic replies.
29
There are 4 types of data types in C++ language.
30
Function Return Type:
A void return type function does not produce a value. A void function executes a task or action
and ends rather than returning a value.
Example:
void printHello() { printf("Hello, world!\n"); }
Let's see the basic data types. It size is given according to 32 bit OS.
31
Type Modifiers in C++
C++ allows the char, int, and double data types to have modifiers preceding them. A modifier
is used to alter the meaning of the base type so that it more precisely fits the needs of various
situations.
The data type modifiers are listed here −
signed
unsigned
long
short
C++ Keywords
C++ keywords play a crucial role in defining the syntax and functioning of the language. They
include reserved words with functions, such as specifying data types, managing program flow,
and activating additional features. Understanding these terms is essential for good C++
programming and enables programmers to build reliable and adaptable software.
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of
32 Keywords in C++ (63) Language which are also available in C language are given below.
A list of 30 Keywords in C++ Language which are not available in C language are given
below.
32
operator template friend private class
For example, suppose the given data is an integer type, and we want to convert it into float type.
So, we need to manually cast int data to the float type, and this type of casting is called the Type
Casting in C++.
int num = 5;
float x;
x = float(num);
x = 5.0
33
cout << " The value of y: " << y << endl;
34
cout << " \n Explicit Type Casting: " << endl;
// use cast () operator to convert int data to float
res = (float) 21 / 5;
cout << " The value of float variable (res): " << res << endl;
return 0;
}
Output:
Implicit Type Casting:
Result: 4
C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operator
o Unary operator
o Ternary or Conditional Operator
o Misc Operator
35
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left.
int data=5+10*10;
The precedence and associativity of C++ operators is given below:
36
Shift << >> Left to right
C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or
other user-defined data types created by the programmer. They are the basic requirement of any
language. Every language has its own rules for naming the identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a program which
are given below:
o Constants
o Variables
o Functions
o Labels
o Defined data types
Some naming rules are common in both C and C++. They are as follows:
37
o The identifier name cannot start with a digit, i.e., the first letter should be alphabetical.
After the first letter, we can use letters, digits, or underscores.
o In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++
identifiers are case-sensitive.
o A declared keyword cannot be used as a variable name.
For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.
Therefore, it proves that identifiers are case-sensitive.
Valid Identifiers
The following are the examples of valid identifiers are:
Result
Test2
_sum
power
Invalid Identifiers
The following are the examples of invalid identifiers:
Sum-1 // containing special character '-'.
2data // the first letter is a digit.
break // use of a keyword.
Differences between Identifiers and Keywords
Identifiers Keywords
Identifiers are the names defined by the programmer to the Keywords are the reserved words
basic elements of a program. whose meaning is known by the
compiler.
It is used to identify the name of the variable. It is used to specify the type of
entity.
It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the underscore. It cannot contain any special
character.
38
The starting letter of identifiers can be lowercase, uppercase or It can be started only with the
underscore. lowercase letter.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else',
'break', etc.
C++ Expression
C++ expression consists of operators, constants, and variables which are arranged according to
the rules of the language. It can also contain function calls which return values. An expression can
consist of one or more operands, zero or more operators to compute a value. Every expression
produces some value which is assigned to the variable with the help of an assignment operator.
(a+b) - c
(x/y) -z
4a2 - 5b +c
(a+b) * (x+y)
o Constant expressions
o Integral expressions
o Float expressions
o Pointer expressions
o Relational expressions
o Logical expressions
o Bitwise expressions
o Special assignment expressions
39
If the expression is a combination of the above expressions, such expressions are known as
compound expressions.
C++ Strings
In C++, string is an object
of std::string class that
represents sequence of
characters. We can perform
many operations on strings
such as concatenation,
comparison, conversion etc.
#include <iostream>
using namespace std;
int main( ) {
string s1 = "Hello";
char ch[] = { 'C', '+', '+'};
string s2 = string(ch);
cout<<s1<<endl;
cout<<s2<<endl;
}
Output:
Hello
C++
Q:-1. Write a program to create a structure “Employee” which contains id, name, salary of
an employee and display all.
40