C++
C++
All variables use data-type during declaration to restrict the type of data to be
stored. Therefore, we can say that data types are used to tell the variables the type
of data it can store. Whenever a variable is defined in C++, the compiler allocates
some memory for that variable based on the data-type with which it is declared.
Every data type requires a different amount of memory.
1. Primitive Data Types: These data types are built-in or predefined data
types and can be used directly by the user to declare variables. example: int,
char , float, bool etc. Primitive data types available in C++ are:
Integer
Character
Boolean
Floating Point
Double Floating Point
Valueless or Void
Wide Character
Primitive data types are predefined types of data, which are supported by the
programming language. For example, integer, character, and string are all
primitive data types.
Non-primitive data types are not defined by the programming language, but
are instead created by the programmer.
Primitive data structure is a data structure that can hold a single value in a
specific location whereas the non-linear data structure can hold multiple
values either in a contiguous location or random locations
The examples of primitive data structure are float, character, integer and
pointer. The value to the primitive data structure is provided by the
programmer. The following are the four primitive data structures:
In case of linear data structure, the data is stored in a sequence, i.e., one
data after another data. When we access the data from the linear data
structure, we just need to start from one place and will find other data in a
sequence.
2. Derived Data Types: The data-types that are derived from the primitive or
built-in datatypes are referred to as Derived Data Types. These can be of
four types namely:
Function
Array
Pointer
Reference
3. Abstract or User-Defined Data Types : These data types are defined by
user itself. Like, defining a class in C++ or a structure. C++ provides the
following user-defined datatypes:
Class
Structure
Union
Enumeration
Typedef defined DataType
primitive data types available in
Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to
2147483647.
Character: Character data type is used for storing characters. Keyword used
for character data type is char. Characters typically requires 1 byte of
memory space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean
data type is bool.
Floating Point: Floating Point data type is used for storing single precision
floating point values or decimal values. Keyword used for floating point data
type is float. Float variables typically requires 4 byte of memory space.
Double Floating Point: Double Floating Point data type is used for storing
double precision floating point values or decimal values. Keyword used for
double floating point data type is double. Double variables typically requires
8 byte of memory space.
void: Void means without any value. void datatype represents a valueless
entity. Void data type is used for those function which does not returns a
value.
Wide Character: Wide character data type is also a character data type but
this data type has size greater than the normal 8-bit data type. Represented
by wchar_t. It is generally 2 or 4 bytes long.
Datatype Modifiers
As the name implies, datatype modifiers are used with the built-in data types to
modify the length of data that a particular data type can hold.
Signed
Unsigned
Short
Long
Below table summarizes the modified size and range of built-in datatypes when
combined with the type modifiers:
The term "unsigned" in computer programming indicates a variable that can hold
only positive numbers. The term "signed" in computer code indicates that a
variable can hold negative and positive values.
Data Type Size (in bytes) Range
short int 2 -32,768 to 32,767
unsigned short int 2 0 to 65,535
unsigned int 4 0 to 4,294,967,295
Int 4 -2,147,483,648 to 2,147,483,647
long int 4 -2,147,483,648 to 2,147,483,647
unsigned long int 8 0 to 4,294,967,295
signed char 1 -128 to 127
unsigned char 1 0 to 255
Float 4
Double 8
long double 12
wchar_t 2 or 4 1 wide character
Output:
Variables
Constants
As the name suggests the name constants are given to such variables or values in
C++ programming language which cannot be modified once they are defined.
They are fixed values in a program. There can be any types of constants like
integer, float, octal, hexadecimal, character constants, etc. Every constant has
some range. The integers that are too big to fit into an int will be taken as long.
Now there are various ranges that differ from unsigned to signed bits. Under the
signed bit, the range of an int varies from -128 to +127, and under the unsigned
bit, int varies from 0 to 255.
Defining Constants:
Below program shows how to use const to declare constants of different data
types:
#include <iostream.h>
#include<conio.h>
void main() {
// int constant
const int intVal = 10;
// Real constant
const float floatVal = 4.14;
// char constant
const char charVal = 'A';
// string constant
const string stringVal = "ABC";
Output:
Integer constant: 10
Floating point constant: 4.14
Character constant: A
String constant: ABC
Types of constants
Numeric Constant
Character Constant
Escape Sequences
Numeric Constant
These have numeric value having combination of sequence of digits i.e. from 0-9
as alone digit or combination of 0-9 with or without decimal point (precision
value) having positive or negative sign. These are further sub-divided into two
categories as:
(i) Integer Numeric Constant
(ii) Float or Real Numeric Constant
(i) Integer Numeric Constant
C++ supports another type of constant: the string. A string is a set of characters
enclosed in double quotes (“). For example: “Welcome to C++” is a string.
You must not confuse strings with characters. A single character constant is
enclosed in single quotes, as in ‘a’. However, “a” is a string containing only one
letter.
For example: “Dinesh”, “Hello”, “2013”, “2013-2020”, “5+3”, “?+!” etc. are
some valid string character constant. These are used for printing purpose or
display purpose in the C++ program’s output statements. These can also be used
for assigning the string data to the character (string) type variables.
(iii) Backslash Character Constants
Enclosing character constants in single quotes works for most printing characters.
A few, however, such as the carriage return, can’t be. For this reason, C++
includes the special backslash character constants, shown below, so that you may
easily enter these special characters as constants.
These are also referred to as escape sequences.
These are used for special purpose in the C++ language. These are used in output
statements like cout etc.
Escape Sequences
Enums or enumerations are generally used when you expect the variable to select
one value from the possible set of values. It increases the abstraction and enables
you to focus more on values rather than worrying about how to store them. It is
also helpful for code documentation and readability purposes.
Here Enumeration name is direction which can only take one of the four specified
values, the dir at the end of the declaration is an enum variable.
#include <iostream.h>
#include<conio.h>
enum direction {East, West, North, South};
void main(){
direction dir;
dir = South;
cout<<dir;
getch();
}
Output:
3
Why use enum in C++
Enums are used only when we expect the variable to have one of the possible
set of values, for example, we have a dir variable that holds the direction.
Since we have four directions, this variable can take any one of the four
values, if we try to assign a another random value to this variable, it will
throw a compilation error. This increases compile-time checking and avoid
errors that occurs by passing in invalid constants.
Another important place where they are used frequently are switch case statements
where all the values that case blocks expect can be defined in an enum. This way
we can ensure that the enum variable that we pass in switch parenthesis is not
taking any random value that it shouldn’t accept.
44
The enum keyword is also used to define the variables of enum type. There are two
ways to define the variables of enum type as follows −
enum colors{red, black};
enum suit{heart, diamond=8, spade=3, club};
The following is an example of enums.
Example
#include<iostream.h>
#include<conio.h>
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
void main() {
cout <<"The value of enum color :
"<<red<<","<<black;
cout <<"\nThe default value of enum suit :
"<<heart<<","<<diamond<<","<<spade<<","<<club;
getch();
}
Output
The value of enum color : 5,6
The default value of enum suit : 0,8,3,4
In the above program, two enums are declared as color and suit outside the main()
function.
enum colors{red=5, black};
enum suit{heart, diamond=8, spade=3, club};
In the main() function, the values of enum elements are printed.
cout <<"The value of enum color : "<<red<<","<<black;
cout <<"\nThe default value of enum suit :
"<<heart<<","<<diamond<<","<<spade<<","<<club;
Compiler Tokens:
2.Identifiers: Identifiers are used as the general terminology for the naming of
variables, functions and arrays. These are user-defined names consisting of an
arbitrarily long sequence of letters and digits with either a letter or the
underscore(_) as a first character. Identifier names must differ in spelling and
case from any keywords. You cannot use keywords as identifiers; they are
reserved for special use. Once declared, you can use the identifier in later
program statements to refer to the associated value. A special kind of identifier,
called a statement label, can be used in goto statements.
There are certain rules that should be followed while naming c identifiers:
3.Constants: Constants are also like normal variables. But, the only difference is,
their values cannot be modified by the program once they are defined. Constants
refer to fixed values. They are also called literals.
Constants may belong to any of the data type
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
4.Strings: Strings are nothing but an array of characters ended with a null
character (‘\0’). This null character indicates the end of the string. Strings are
always enclosed in double-quotes. Whereas, a character is enclosed in single
quotes in C and C++.Declarations for String:
char string[20] = {‘w’, ’e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’, ‘\0’};
char string[20] = “welcome”;
char string [] = “welcome”;
when we declare char as “string[20]”, 20 bytes of memory space is allocated
for holding the string value.
When we declare char as “string[]”, memory space will be allocated as per the
requirement during the execution of the program.
5.Special Symbols: The following special symbols are used in C having some
special meaning and thus, cannot be used for some other purpose.[] () {}, ; * = #
Brackets[]: Opening and closing brackets are used as array element reference.
These indicate single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and
function parameters.
Braces{}: These opening and ending curly braces mark the start and end of a
block of code containing more than one executable statement.
Comma (, ): It is used to separate more than one statements like for separating
parameters in function calls.
Colon(:): It is an operator that essentially invokes something called an
initialization list.
Semicolon(;): It is known as a statement terminator. It indicates the end of
one logical entity. That’s why each individual statement must be ended with a
semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication
of variables.
Assignment operator(=): It is used to assign values and for the logical
operation validation.
Pre-processor (#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.
6.Operators: Operators are symbols that trigger an action when applied to C++
variables and other objects. The data items on which operators act upon are called
operands.
Depending on the number of operands that an operator can act upon, operators
can be classified as follows:
Unary Operators: Those operators that require only a single operand to act
upon are known as unary operators.For Example increment and decrement
operators
Binary Operators: Those operators that require two operands to act upon are
called binary operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
b. Comma Operator:
The comma operator (represented by the token) is a binary operator that
evaluates its first operand and discards the result, it then evaluates the second
operand and returns this value (and type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator. (See this article for reference)
c. Conditional Operator :
The conditional operator is of the form Expression1? Expression2:
Expression3.
Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of
Expression3.
We may replace the use of if..else statements with conditional operators.
Increment and Decrement operator:
In C++, Increment operators are used to increase the value of a variable by 1.
This operator is represented by the ++ symbol. The increment operator can either
increase the value of the variable by 1 before assigning it to the variable or can
increase the value of the variable by 1 after assigning the variable. Thus it can be
classified into two types:
Pre-Increment Operator
Post-Increment Operator
1) Pre-increment operator: A pre-increment operator is used to increment the
value of a variable before using it in an expression. In the Pre-Increment, value is
first incremented and then used inside the expression.
Syntax:
a = ++x;
Here, if the value of ‘x’ is 10 then the value of ‘a’ will be 11 because the value of
‘x’ gets modified before using it in the expression.
Output
Pre Increment Operation
a = 11
x = 11
2) Post-increment operator: A post-increment operator is used to increment the
value of the variable after executing the expression completely in which post-
increment is used. In the Post-Increment, value is first used in an expression and
then incremented.
Syntax:
a = x++;
Here, suppose the value of ‘x’ is 10 then the value of variable ‘a’ will be 10
because the old value of ‘x’ is used.
Output
Post Increment Operation
a = 10
x = 11
The scope resolution operator is used to reference the global variable or member
function that is out of scope. Therefore, we use the scope resolution operator to
access the hidden variable or function of a program. The operator is represented as
the double colon (::) symbol.
For example, when the global and local variable or function has the same name in
a program, and when we call the variable, by default it only accesses the inner or
local variable without calling the global variable. In this way, it hides the global
variable or function. To overcome this situation, we use the scope resolution
operator to fetch a program's hidden variable or function.
#include <iostream.h>
#include<conio.h>
// declare global variable
int num = 50;
void main ()
{
// declare local variable
int num = 100;
Output
int x; // Global x
void main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
getch( );
}
Output:
Value of global x is 0
Value of local x is 10
#include<iostream.h>
#include<conio.h>
void main( )
{
int m = 20;
{
int k = m;
int m = 30;
cout<<”We are in inner block\n”;
cout<<”k=”<<k<<”\n”;
cout<<”Local m =”<<m<<”\n”;
cout<<”Global m = “<< : :m<<”\n”;
}
getch( );
}
Output:
We are in inner block
k = 20
Local m = 30
Global m = 10
new operator
The new operator denotes a request for memory allocation on the Free Store. If
sufficient memory is available, new operator initializes the memory and returns
the address of the newly allocated and initialized memory to the pointer variable.
Syntax to use new operator: To allocate memory of any data type, the syntax
is:
Example:
delete operator
delete p;
delete q;
#include <iostream.h>
#include<conio.h>
void main() {
// declare an int pointer
int* pointInt;
getch();
}
Output
45
45.45
delete pointInt;
delete pointFloat;
Typecasting is making a variable of one type, such as an int, act like another type,
a char, for one single operation. To typecast something, simply put the type of
variable you want the actual variable to act as inside parentheses in front of the
actual variable. (char) a will make 'a' function as a char.
#include <iostream.h>
#include<conio.h>
void main( )
{
double a = 21.09399;
float b = 10.20;
int c ;
c = (int) a;
cout << "Line 1 - Value of (int)a is :" << c << endl ;
c = (int) b;
cout << "Line 2 - Value of (int)b is :" << c << endl ;
getch( );
}
When the above code is compiled and executed, it produces the following result −
Line 1 - Value of (int)a is :21
Line 2 - Value of (int)b is :10
Type conversion is the process that converts the predefined data type of one
variable into an appropriate data type. The main idea behind type conversion is to
convert two different data type variables into a single data type to solve
mathematical and logical expressions easily without any data loss.
For example, we are adding two numbers, where one variable is of int type and
another of float type; we need to convert or typecast the int variable into a float to
make them both float data types to add them.
Type conversion can be done in two ways in C++, one is implicit type
conversion, and the second is explicit type conversion. Those conversions are
done by the compiler itself, called the implicit type or automatic type conversion.
The conversion, which is done by the user or requires user interferences called the
explicit or user define type conversion. Let's discuss the implicit and explicit type
conversion in C++.
The implicit type conversion is the type of conversion done automatically by the
compiler without any human effort. It means an implicit conversion automatically
converts one data type into another type based on some predefined rules of the C+
+ compiler. Hence, it is also known as the automatic type conversion.
For example:
1. int x = 20;
2. short int y = 5;
3. int z = x + y;
In the above example, there are two different data type variables, x, and y, where x
is an int type, and the y is of short int data type. And the resultant variable z is also
an integer type that stores x and y variables. But the C++ compiler automatically
converts the lower rank data type (short int) value into higher type (int) before
resulting the sum of two numbers. Thus, it avoids the data loss, overflow, or sign
loss in implicit type conversion of C++.
Order of the typecast in implicit conversion
The following is the correct order of data types from lower rank to higher
rank:
1. bool -> char -> short int -> int -> unsigned int -> long int -> unsigned lo
ng int -> long long int -> float -> double -> long double
#include <iostream.h>
#include<conio.h>
void main()
{
int num; // declare int type variable
double num2 = 15.25; // declare and assign the double variable
Output
In the above program, we have declared num as an integer type and num2 as the
double data type variable and then assigned num2 as 15.25. After this, we assign
num2 value to num variable using the assignment operator. So, a C++ compiler
automatically converts the double data value to the integer type before assigning it
to the num variable and print the truncate value as 15.
Explicit type conversion
Conversions that require user intervention to change the data type of one variable
to another, is called the explicit type conversion. In other words, an explicit
conversion allows the programmer to manually changes or typecasts the data type
from one variable to another type. Hence, it is also known as typecasting.
Generally, we force the explicit type conversion to convert data from one type to
another because it does not follow the implicit conversion rule.
Program to convert one data type into another using the assignment
operator
Let's consider an example to convert the data type of one variable into another
using the assignment operator in the C++ program.
#include <iostream.h>
#include<conio.h>
void main ()
{
// declare a float variable
float num2;
// initialize an int variable
int num1 = 25;
Output
Comments in C++
Multi-line comment
Represented as /* any_text */ start with forward slash and asterisk (/*)
and end with asterisk and forward slash (*/).
It is used to denote multi-line comment. It can apply comment to more
than a single line.
/*Comment starts
continues
continues
.
.
.
Comment ends*/
Example: This example goes same for C and C++ as the style of
commenting remains same for both the language.