An operator is a symbol that performs a specific mathematical or logical operation on operands. Example: Addition : 2 + 3, where 2 and 3 are the operands and + is the operator.
We can say that operators are the foundation of any programming language, the program is incomplete without the operators as we use them in all of our programs.
Following are the types of Operators in C++.
Arithmetic Operators
Increment and Decrement Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Other Operators
C++ Arithmetic Operators
These are used to perform mathematical operations on operands such as addition, subtraction, multiplication, division etc.
operator
description
+
addition adds two operands. eg, a+b.
-
subtraction subtracts two operands. eg, a-b.
*
multiplication multiplies two operands. eg, a*b.
/
division divides the operand by the second. eg, a/b.
%
modulo returns the remainder when the first operand is divided by the second. For example, a%b.
These are the Unary Operators as they operate on a single operand. They are ++ and -- operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1. There are two kinds of Increment and Decrement Operators.
Post-Increment or Post-Decrement: First, the value is used for operation and then incremented or decremented. Represented as a++ or a–.
Pre-Increment Pre-Decrement: Here First the value is incremented or decremented then used for the operation. Represented as ++a or –a.
Click Here for example of Increment and Decrement operators.
C++ Assignment Operators
Assignment operators are used in a program to assign a value of the right-hand side to the left-hand side as shown below.
//10 is assign to the variable a
int a = 10;
//the value of b (10) is assigned to a
int b = 20;
int a = b;
These are the short version formed by combining the two operators. For example Instead of writing, int a = a+5, we can write a += 5.
Following are the list of assignment operators used in C++.
Operator
Description
=
Simple assignment operator, Assigns values from right side operands to left side operand. a = b + c;
+=
Add AND assignment operator, It adds the right operand to the left operand and assigns the result to the left operand. a += b
-=
Subtract AND assignment operator, It subtracts the right operand from the left operand and assigns the result to the left operand. a -= b
*=
Multiply AND assignment operator, It multiplies the right operand with the left operand and assigns the result to the left operand. a *= b
/=
Divide AND assignment operator, It divides left operand with the right operand and assigns the result to the left operand. a /= b
%=
Modulus AND assignment operator, It takes modulus using two operands and assigns the result to the left operand. a %= b
<<=
Left shift AND assignment operator. a <<= 2
>>=
Right shift AND assignment operator. a >>= 2 or a = a >> 2
&=
Bitwise AND assignment operator. a &= 2 or a = a & 2
^=
Bitwise exclusive OR and assignment operator. a ^= 2 or a = a ^ 2
|=
Bitwise inclusive OR and assignment operator. a |= 2 or a = a | 2
Click Here for example of Assignment Operators operators.
C++ Relational Operators
These operators are used to compare two values and return Boolean results. For example: it checks if the operand is equal to another operand or not or an operand is greater than the other operand or not or checks less than between two values, etc.
List of relational operators in C++:
Operator
Name
Example
==
Equal to.
A == B
!=
Not equal.
A != B
>
Greater than.
A > B
<
Less than.
A < B
>=
Greater than or equal to.
A >= B
<=
Less than or equal to.
A <= B
Click Here for example of Relational Operators operators.
C++ Logical Operators
Logical Operators are used in conditional statements and loops for evaluating a condition with binary values. They are used to combine two different expressions together.
The following are the C++ Logical Operators. Assume X holds the value 1 and Y holds 0
Operator
Description
Example
&& (logical and)
If both the operands are non-zero, then the condition becomes true.
(X && Y) is false
|| (logical or)
If any of the two operands are non-zero, then the condition becomes true.
(X || Y) is true
! (logical not)
Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(X && Y) is true
Click Here for example of Logical Operators operators.
C++ Bitwise Operators
Bitwise operators are used to perform a bit-level operation on operands. They are used in testing, setting, or shifting the actual bits in a program.
You can see the truth table below.
p
q
p & q
p | q
p ^ q
~p
0
0
0
0
0
1
0
1
0
1
1
1
1
1
1
1
0
0
1
0
0
1
1
0
Below are the list of Bitwise operators:
Operators
Name of operators
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR
~
Bitwise complement
<<
Shift left
>>
Shift right
Click Here for example of Bitwise Operators operators.
Other Operators
Apart from the above operators, there are various other operators used in C++ programming. They are listed below.
sizeof()
It returns the size of a variable, constant, array, etc. sizeof is a keyword in C++. Example: sizeof(int); // returns 4
?:
The ternary operator (or Conditional operator) returns a true or false after checking the condition. It works like if..else statement. Example: int a = 10; a > 5 ? cout << "true" : cout << "false"
,
Comma Operator, this operator is used to link related operators together. The value of the entire comma expression is the value of the last expression of the comma-separated list. Example: a, c, d = 0, z;
&
This is a pointer operator, used to point the address of a variable, or we can say that it represents the memory address of the operand to which it points. Example: &a;, This points to the actual address of the variable a.
*
This is also a pointer variable, Indirection Operator. It returns the value of the variable that it points to.
.
dot operator, this operator is used to access the members of the class, structure and objects. Example: stud1.score = 90;
->
This operator is usually seen used with pointers to access the class or struct variables. Example: ptr->score = 90;
Operators Precedence in C++
In a program, there may be an expression that uses more than one operator, in such case operator precedence determines which is to be evaluated first and next.
Let us take an example:
int result = 10 + 5 * 10;
//Output:
60
The output of the above expression is 60 because the precedence of multiplication is higher than the addition. So first (5 * 10) is evaluated and then 10 is added to the result.
The following shows the precedence and associativity of C++ operators:
Associativity refers to the direction of the operators to be evaluated first and next. It may be right to left or left to right.
A keywords are the reserved words in programming language with a specific features for each keyword. Keywords always starts with the lower case and cannot be a variable name or constant name. These are predefined by the program and their value cannot be changed.
Example: int, float, public, etc.
The following is the list of 30 keywords in C++ that are also available in C programming language.
auto
break
case
char
const
double
else
enum
extern
float
int
long
register
return
short
struct
switch
typedef
union
unsigned
continue
default
do
for
goto
if
signed
sizeof
static
void
volatile
while
The following is the list of 30 keywords in C++ that are not available in C programming language.
asm
dynamic_cast
namespace
reinterpret_cast
bool
explicit
new
static_cast
false
catch
operator
template
friend
private
class
this
inline
public
throw
const_cast
delete
mutable
protected
true
try
typeid
typename
using
virtual
wchar_t
Identifiers
Identifiers are nothing but the name assigned to the entities such as variables, functions, arrays, or other user-defined data types. Identifiers are the basics need of programming language.
The name assigned to the entities is unique so that it can be identified during the execution of the program. Identifiers cannot be used as Keywords.
Example: int number;, number being an identifier.
Rules for naming identifiers:
Identifiers are case-sensitive that is uppercase and lowercase letters are distinct.
The first letter of identifiers must be a letter or underscore. After the first letter, you can use digits.
White spaces are not allowed.
A keyword cannot be used as an identifier.
Some valid and invalid identifiers:
//Valid
Number
result1
_multiply
S2C
//Invalid
Number-2 //special character '-' is present.
3Sum //started with digit
int // int is a keyword
Constant in C++ refers to the values in the program whose value during the entire execution of the program. And these fixed values are called Literals.
These constants may be any of the data types present in C++ such as Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
They are just like the regular variables, the only difference is that their value cannot be changed once they are defined in the program. The constant is defined by the keyword const in a program.
Syntax:
const float PI = 3.14;
The constant value cannot be modified later in the program.
const float PI = 3.14;
PI = 3.0 // Compiler Error because PI is a constant.
Although, there are two ways in which you can define a constant. They are:
By the use #define preprocessor.
Another with keyword const itself.
1. #define: Syntax
#define identifier value
Example: C++ example for constant.
#include <iostream>
using namespace std;
//constant
#define SIDE 5
int main()
{
int sq_area;
sq_area = SIDE * SIDE ;
cout <<"The square area: "<<sq_area;
return 0;
}
//OUTPUT
The square area: 25
2. constant: Syntax
const data-type variable_name = value;
Example: C++ example for constant.
#include <iostream>
using namespace std;
int main()
{
//constant
const int side = 5;
int sq_area;
sq_area = side * side;
cout <<"The square area: "<<sq_area;
return 0;
}
//OUTPUT
The square area: 25
C++ Literals
As mentioned above, literals are the fix value. They are the notation used in a program for fix value. For example:1, 2.5, 'c' etc. are the literals because you cannot assign different values to these terms.
The following are the various literals in C++ programming.
1. Integers Literals
An integer literal is a numeric value without any fractional or exponential part. The following are the three integer literal in C++:
The Integer Literal may have U or L as a suffix for unsigned and long integers
22 // decimal
0154 // octal
0x7B // hexadecimal
5 // int
12u // unsigned int
36l // long
2. Floating-point Literals
Floating-point literals are the numeric value with fractional part or exponential part. The signed exponent is introduced by e or E.
Example:
7.1479 //Decimal Form
23.5e-14 //Exponential Form
Note: e-14 means 10^-14
3. Boolean Literals
There are two Boolean literals and they are the keyword true and false. They are part of standard C++ keywords.
4. character-literal
A character literal refers to the single character enclosed within a single quote. Example: 'b', 'A', '5', ')', '}' etc.
A character Literal may be an escape sequence that is '\t' or it can be universal character that is ‘\u02C0’.
Escape Sequence: There are some characters with the special meaning when used with backslash (\)that cannot be typed but only when used such as the new line ( '\n'), tab ( '\t'), etc.
The following are the list of some escape sequence.
Escape sequence
Meaning
\\
\ character
\’
‘ character
\”
” character
\?
? character
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
5. String Literals
A string literal refers to the sequence of characters enclosed in double quote. A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
Example:
"hello World\n" \\string constant with a new line
"" \\NULL String constant
"x" \\String constant with single character.
Later on this C++ tutorial, you will learn more on String.
In any programming language, the scope is a region which is can be defined as the extent up to which something is valid. All the variables used in a program have their extent of use and if used out of that extent or boundary, they do not hold their values. Hence this boundary is referred to as the scope of a variable
These boundaries are referred to curly braces “{}“ in a program. Based on their scope, there are two types of variables.
Local variables: inside a function or a block.
Global variables: outside of all functions.
Formal parameters: function parameters.
block: refers to anything between ‘{‘ and ‘}’.
1. Local variables:
Local variables are the variables that are declared within the body of the function or block. These types of variables can only be used within a block where it is created or declared, it has no existence outside the block.
Example: C++ example using local variables.
#include <iostream>
using namespace std;
//user-defined function
int add(int a, int b)
{
return a + b;
}
//main function
int main()
{
/*local variables
only used inside main function*/
int x = 10, y = 20;
int z;
z = add(x, y);
cout << "value of z: " << z;
return 0;
}
Output:
value of z: 30
Let us see one more example where the variable with same name can be used in different function holding different values.
#include <iostream>
using namespace std;
void add()
{
int x = 2, y = 10, result;
result = x + y;
cout << "Addition result: " << result;
}
void multiply()
{
int x = 3, y = 5, result;
result = x * y;
cout << "\nSubstraction result: " << result;
}
//main function
int main()
{
add();
multiply();
return 0;
}
Output:
Addition result: 12
Substraction result: 15
2. Global Variable
These variables are available to use throughout the program that is they have their scope throughout the program. They are defined outside the function (including main()), usually, you will see them at the top of any program.
After its declaration in a program, a global variable can be used inside any function present in a program.
Example: C++ example using global variables.
#include <iostream>
using namespace std;
// Global variable declaration:
int g;
int main ()
{
// Local variable declaration adn intialization:
int a = 20, b = 30;
//use of global variable
g = a + b;
cout << "g holds: " << g;
return 0;
}
Output:
g holds: 50
Let us see one more example where the local variable takes preference.
#include <iostream>
using namespace std;
//global variable
int g = 20;
void testFunction()
{
//overrides the g value with 30
g = 30;
cout << g << endl;
}
int main()
{
testFunction();
//local variable
int g = 50;
cout << g << endl;
return 0;
}
Output:
30
50
As you can see in the above program, g is declared global with a value of 20, but again it is initialized inside testFunction() with the value of 30. And present value(30) overrides the previous value (20) and prints 30.
In the main function again g is defined and initialized (making it local variable) with 50 that overrides the 20.
The variable is the basic unit of storage that holds the value while the program is executed. We can also say that it is a name given to the memory location. A variable is defined by data-types provided by C++.
These variables belongs to the types in c++ which are the following:
int: stores integers (whole numbers), such as 120 or -120.
double: single-precision floating-point value with decimals, such as 29.99 or -29.99.
char: stores single characters, such as ‘a’ or ‘B’ within single quotes.
string: stores text within double-quotes such as “Hello World”.
bool: stores true or false values.
void : Represents the absence of type.
wchar_t : A wide-character type.
Rules for naming C Variables:
A variable name must begin with a letter or underscore.
They are case sensitive that is Score and score are not the same.
They can be constructed with digits, letters and underscore.
No special symbols are allowed other than underscores.
A variable name cannot be a keyword. Example, int cannot be a variable name as it is an in-built keyword.
Defining a variable:
Defining a variable means the compiler has to now assign storage to the variable because it will be used in the program. You can directly define a variable inside the main() function and use it.
To define a function we must provide the data type and the variable name. We can even declare multiple variables of the same data type in a single line by using a comma to separate them.
type variable_list_name, where type must be the valid c++ data-type.
Example:
int i;
char c, ch; //multiple variable in single line
float f, amount, salary;
double db;
Declaration of Variables
The declaring variable is useful for multiple files and the variable is declared in one of the files and is used during linking the file.
Declaration of variables must be done before they are used in the program. Declaration does the following things.
It tells the compiler what the variable name is.
It specifies what type of data the variable will hold.
A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. Keyword extern is used for the declaration of variables at any place in the program.
extern int a;
extern float b, c; //multiple declaration
Initialization of Variables
initialization is simply giving the variable a certain initial value which may be changed during the program.
A variable can be initialized and defined in a single statement, syntax:
int a; // declaration
a = 10; // initialization
//can be done in single step too
int a = 20;
float x = 20.5, y = 11.25; //multiple initialization
NOTE: If a variable is declared and not initialized by default it will hold a garbage value.
If you declare the variable which is already been declared then it will throw a compile time error. Example:
int x, y; //declaration
x = 10; //initialization
y = 20; //initialization
int j = i+j; //compile time error
C++ Program to demonstrate the declaration, definition and initialization of vaariables.
#include <iostream>
using namespace std;
// Variable declaration:
extern int x, y;
extern int z;
extern float f;
int main()
{
// Variable definition:
int x, y;
int z;
float f;
// variable initialization
x = 10;
y = 20;
z = x + y;
cout << z << endl;
f = 19.0 / 3.0;
cout << f << endl;
return 0;
}
While writing a program, we store the information by creating a variable. These variables are nothing but the name given to some unspecified memory location. Now the information can be character type, integer type, double, float etc.
A data type specifies the type of data that a variable can store such as integer, floating, character, double, boolean etc. Each of these data types varies in storage size that will be shown below in the table.
A data type or simply type is an attribute of data that tells the compiler or interpreter how the programmer intends to use the data.
Types of data types in C++:
Primitive Data Types: integer, float, character, double, boolean, void and wchar_t.
Derived Data Types: Arrays, Pointers and Function.
Abstract or User-Defined Data Types: Structure, Union and Enum.
Primitive Data Types:
These are the predefined data types that are already defined in C++ such as integer, float, character, double, boolean, void and wchar_t.
Basic Built in Datatypes in C++:
The memory size of data types may change according to 32 or 64 bit Operating System (OS).
data type
desc and size
char
for character storage (1 byte)
int
for integral number (2 bytes)
float
single precision floating point (4 bytes)
double
double precision floating point numbers (8 bytes)
bool
Boolean (True or False)
void
Without any Value
wchar_t
Wide Character. (2 or 4 bytes)
**Wide Character(wchar_t): This type should be avoided because its size is implementation-defined and not reliable.
How above basic data type is written in code, example:
char ch = 'A'; // character type
int num = 10; // integer type
float num = 627.5485; // floating point type
double num = 20054.86798; //double type (e is for exponential)
bool b = true; //boolean type returns true or false
Modifiers in C++:
The modifiers for the built-in data is used specify them more precisely and even increase the range. Following modifiers are used with the above basic data types:
signed: includes both positive and negative numbers.
unsigned: refers to the numbers that are always without any sign, that are always positive.
short: minimum values that a data type will hold.
long: maximum values that a data type will hold.
Size hierarchy:short int < int < long int Size hierarchy for floating point numbers is:float < double < long double
Data Types (s & u)
Memory Size
Range
char
1 byte
-128 to 127
signed char
1 byte
-128 to 127
unsigned char
1 byte
0 to 127
short
2 byte
-32,768 to 32,767
signed short
2 byte
-32,768 to 32,767
unsigned short
2 byte
0 to 32,767
int
2 byte
-32,768 to 32,767
signed int
2 byte
-32,768 to 32,767
unsigned int
2 byte
0 to 32,767
short int
2 byte
-32,768 to 32,767
signed short int
2 byte
-32,768 to 32,767
unsigned short int
2 byte
0 to 32,767
long int
4 byte
signed long int
4 byte
unsigned long int
4 byte
float
4 byte
double
8 byte
long double
10 byte
Derived Data Types:
Also known as Non-Primitive data type. These are:
Arrays
Pointers
Function.
These topics are covered in detail in separate tutorials.
Abstract or User-Defined Data Types:
These are the type, that user creates as a class or a structure. There three types of user-defined data types in C++:
struct
union
enum
These topics are covered in detail in separate tutorials.
This section is important, before diving into the main content of the C++ program, you need to learn the basic syntax of C++. You need to know in which manner C++ code is written. C++ is the collection of classes and objects that communicate with each other via. method.
C++ Program Structure
Let us start by looking at the simple hello world program in C++.
// Header file for input/output
#include<iostream>
using namespace std;
// main function from where the execution of program starts
int main()
{
//prints hello world
cout<<"Hello World";
return 0;
}
// Header file for input/output: The line starting with // are the comment lines that are not included during execution but these are for the programmer to comment on the necessary section as required. It is considered a good practice to use comments. For multiple comment lines, you start with /* and end with */ and write in between.
#include<iostream>: This is the header files used for executing the standard input and output function in C++. There are several header files that are very useful for the program. The line starting with # are directives that are processed by the preprocessor.
Some of the header files used in C++:
<iostream>
Contains C++ standard input and output functions
<cmath>
Contains math library functions
<ctime>
Contains function for manipulating the time and date
<fstream>
Contains function for functions that perform input from files on disk and output to files on disk
using namespace std;: This line tells the compiler to use a group of functions that are part of the standard library (std). A semi-colon ‘;’ is used to end a statement.
int main(): It is the main function of the program from where the execution of the program begins. int is a type that shows that the function returns integer type. If you don’t want to return anything then simply use the void instead of int.
{ ..... }: Opening and Closing braces shows the beginning and the ending of the main function in a program.
cout<<"Hello World";: This line is responsible for displaying the Hello World on the screen. coutis the standard out function present in <iostream> header file.
return 0; : This statement in a program is used to return a value from the function and also indicating the end of the function. You can usually use it to return some result of the calculation and such.
Compilation and Execution of C++ Program
There are steps to compile and run the C++ program n your computer. You need to save, compile and run, follow the below steps.
First, open a text editor(eg notepad) on your computer and write your C++ code.
Now save the file as file_name.cpp. Example: hello.cpp.
Then open a command prompt and go to the directory where you have saved the file.
And on the command prompt type 'g++ hello.cpp‘ and press enter to compile your code. And if no error is found then the command prompt will take you to the next line.
Now, type ‘a.out‘ to run your program.
Then Hello world will be printed on the screen (considering the above code).
It will look something like this:
$ g++ hello.cpp
$ ./a.out
Hello World
Always make sure that you are in the same directory where you have saved the file.
C++ is a powerful general-purpose, case-sensitive, free-form programming language that supports object-oriented, procedural, and generic programming. It is a mid–level language as it comprises both low and high-level language features.
C++ programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey. It was developed as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983.
C++ runs on a variety of platforms, such as Windows, Mac OS, and also in the various versions of the UNIX system. C++ can be used in various platforms for development purposes such as for the development of operating systems, browsers, games, etc.
Object-Oriented Programming
C++ supports object-oriented programming(OOPs) and hence stands on four major components and those are.
Inheritance
Polymorphism
Encapsulation
Abstraction
Standard Libraries of C++
C++ is consists of three major parts:
The first one is the core library which gives the building blocks of the programming, such as variables, data types, and literals, etc.
Second is the Standard library that gives a set of functions manipulating strings, files, etc.
The third one is The Standard Template Library (STL) that includes the set of methods manipulating data structure, etc.
What are the Features of C++ programming Language?
C++ is an Object-Oriented Programming Language, which is its main feature. It can create and destroy objects while programming. As it is an enhancement to C, hence it possesses all the features offered by C along with its new important feature (Object-Oriented Programming, operator overloading, error handling, etc).
What are the Features of C++ programming Language?
Object-Oriented Programming (OOP)
Simple
Platform or Machine Dependent/Portable
High-Level Language
Multi-paradigm programming language
Case Sensitive
Compiler based
Speed
Rich in Library
Memory Management
Pointer and Recursion
1. Object-Oriented Programming (OOP)
C++ is an Object-Oriented Programming Language and it is its main feature. It provides a modular structure for programs that means OOP divides the program into a number of objects and makes it simpler and easier for maintainance which is not provided in Procedure-oriented programming language such as C. Therefore understanding OOP is an important step to learn Java Programming.
C++ follows four main concepts of OOP those are abstraction, data encapsulation, data hiding, and polymorphism.
2. Simple
It is a simple programming language in the sense of a structured approach that is the program can be broken down into parts and can be resolved modularly. This helps the programmer to recognize and understand the problem easily.
3. Platform or Machine Independent/Portable
Platform Dependent language refers to those languages that are executed only on that operating system where it is developed but cannot be executed on any other Operating system. And C++ is of those languages.
Although portability refers to using the same piece of code on various environment with little or no change.
4. High-Level Language
C++ is a high Level language, making it easier to understand as it is closely associated with the human-comprehensible language that is English.
It also supports the feature of low-level language that is used to develop system applications such as kernel, driver, etc. That is why it is also known as mid-level language as C++ has the ability to do both low-level & high-level programming.
5. Multi-paradigm programming language
C++ is a language that supports object-oriented, procedural and generic programming. It supports at least 7 different styles of programming. This makes it very versatile.
6. Case Sensitive
Similar to C, C++ also treats the lowercase and uppercase characters in a different manner. For example, the keyword “cout’ (for printing) changes if we write it as ‘Cout’ or “COUT”. But this problem does not occur in other languages such as HTML and MySQL.
7. Compiler-based
C++ is a compiler-based programming language, unlike Java or Python which are interpreter-based. This feature makes C++ comparatively faster than Java or Python language.
8. Speed
It is a compile-based, hence the compilation and execution time of C++ language is fast.
9. Rich in Library
C++ offers a library full of various in-built function that makes the development with C++ much easier and faster. These functions are present in the various header files and header files are included at the beginning of the program depending on which function the programmer needed to use.
Some of the header files used in C++:
<iostream>
Contains C++ standard input and output functions
<cmath>
Contains math library functions
<ctime>
Contains function for manipulating the time and date
<fstream>
Contains function for functions that perform input from files on disk and output to files on disk
10. Memory Management
C++ has this feature that allows us to allocate the memory of a variable in run-time. This is known as Dynamic Memory Allocation. There is a function called free() that allows us to free the allocated memory.
11. Pointer and Recursion
Unlike Java, C++ supports pointers for direct interaction with the memory. Pointer is used for memory, structures, functions, array etc. It provides various solution for the memory related problems in a program.
It provides code reusability for every function that is the recursion.