01 of 02 parts
Get Part 2 from https://www.slideshare.net/ArunUmrao/introduction-to-c-programming-for-beginners-by-arunumrao-2-of-2-250786026
Introduction to c++ programming, Introduction to c++ programming, Introduction to c++ programming, Introduction to c++ programming, Introduction to c++ programming,
9. 1.1. INPUT/OUTPUT 9
1Basic C++
C++ is a high level programming language and backbone of Computer & Information
Technology. C++ is an extension of C in functionality. It has hundreds of ready-made
libraries and functions. Now we will study the basic functionality and procedure of C++.
The compiler used in this book is ‘gcc’ in ‘cygwin’ or ‘MingW’ package. The C++
compiler for all programs given in this book is g++.
1.1 Input/Output
Like the printf and scanf of C, to put the contents in out-stream and fetch the contents
from in-stream respectively, C++ uses operators ‘<<’ and ‘>>’ for this purposes.
✞
1 int a = 5;
cout << a; /* Put value of ‘a’ in out stream*/
3 cin >> a; /* Take user ’s input and assign it to ‘a’*/
✌
✆
1.1.1 Minimal Structure
The minimal structure of C++ program contains header and main() function. Each
program must have main() function as each program being executed from here. Header
contains header files to include libraries or ready-made C++ functions. cout is used to
print contents in out-stream. See the example below:
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 cout << "Hello World!!";
return 0;
7 }
✌
✆
When this program runs, output of the program appears in console window as given
below:
✞
Hello World!!
✌
✆
In above example,
✞
1 #include <cstdlib >
#include <iostream >
✌
✆
tells to C++ compiler to find the standard header files and include them to the program.
cstdlib contains description of standard C libraries and iostream contains the standard
10. 10 Basic C++
input/output functions which are used to sent messages to user or to read inputs from a
user. We can use other old C libraries in C++. Old C libraries, to be included in C++,
are started with letter ‘c’. For example, math.h of C, is added in header as cmath in C++.
cstdlib header file has many native C function and standard library functions. Similarly
other old C header files can be searched and added in header of the C++ program.
✞
int main (int argc , char ** argv )
✌
✆
is the main function, where a program begins. Prefix int to main() function has meaning
that main() function will return an integer to the operating system when it is finished.
Though the default return value of main() function is integer but return value as void is
also acceptable. The compiler shows warning when return value from the main function
is not integer.
✞
1 cout << " Hello World!!";
✌
✆
is the statement that actually puts the message into the screen. cout is the formatted
printing function and is followed by symbol <<. << is a C++ insertion operator which
adjusts its behavior to fit the type of data that follows it.
✞
1 return 0;
✌
✆
will return zero to the operating system. ‘Return of 0’ is indication of successful execution
of program. Return value other than ‘0’ indicates run failure or error in execution of
program. C++ uses conventional code grouping structure. A function or a code block
are grouped by curly braces, i.e. {...}. All the variable defined inside the group {...} have
local scope. A semicolon is used to terminate the line. endl is used to add new line.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
7 /* This is the beginning of a ‘block’*/
int i = 6; /* variable of this ‘block’*/
9
{/* Start of new block. Block has own scope.*/
11
/* There is a variable ‘i’, as outside to *
13 * new block. Because it is in a different *
* ‘block’, therefore , it does not change *
15 * the value of old ‘i’, of outside block!*/
int i = 5;
17 cout << i; /* Prints ‘5’ in the screen */
cout << endl ; /* Add a new line .*/
19
}/* End of new block. */
21
/* Now we’re back into the old block */
11. 1.1. INPUT/OUTPUT 11
23 cout << i; /* Prints ‘6’ in the screen */
25 return 0;
}
✌
✆
✞
5
6
✌
✆
Also see the example given below.
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
int main (int argc , char ** argv ) {
6 int x = 1; /* Original x */
8 cout << "x in outer block: " << x << endl ;
10 { /* Begin of new block. */
12 int x = 2; /* New x, hides original x */
cout << "x in inner block: " << x << endl ;
14
} /* End of new block. */
16
cout << "x in outer block: " << x << endl ;
18
for (; x < 5; x++) { /* Original x */
20
int x = 10; /* New x, hides original x */
22 x++;
cout << "x in while loop : " << x << endl ;
24
}
26
cout << "x in outer block: " << x << endl ;
28 return 0;
}
✌
✆
✞
x in outer block: 1
x in inner block: 2
x in outer block: 1
x in while loop : 11
x in while loop : 11
x in while loop : 11
x in while loop : 11
x in outer block: 5
✌
✆
(...) bracket is used to change the precedence of an expression. See the example below:
12. 12 Basic C++
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
int i;
6 /* First 2+3=5 is evaluated and*
*it is assigned to i. Now , 3*
8 *is added to i and j=i or = 8*/
int j = (i = 2 + 3) + 3;
10 cout << "(i = 2 + 3) + 3 = " << j;
12 return 0;
}
✌
✆
✞
(i = 2 + 3) + 3 = 8
✌
✆
To set the value of global variable ‘::’ operator is used. See the example given below:
✞
1 #include <iostream >
using namespace std;
3 int x;
5 int main (int argc , char *argv []) {
int x = 1; // Local x variable . Hides to global x
7 cout << x << "n"; // Print to local x value
::x = 2; // Assign to global x
9 cout << ::x << "n"; // Print to global x value
x = 3; // Assign to local x
11 cout << x << "n"; // Print to local x value
}
✌
✆
✞
1
2
3
✌
✆
1.1.2 Out Stream
ostream is object of out-stream, that can write sequences of characters and represent
other kinds of data. Specific members are provided to perform these output operations.
This class contains member class sentry, member functions flush, operator <<, put, seekp,
tellp, write, and including protected members, operator = and swap. cout is used to print
stuff in output stream. This object is used to put contents in output screen.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
13. 1.1. INPUT/OUTPUT 13
cout << "Hello World!!";
7 return 0;
}
✌
✆
On execusion of the program output on output console will be looked like
✞
Hello World!!
✌
✆
It reference to the address of memory where the contents are to be put. Therefore,
if cout is let to put the contents of itself, then it flushes the address of itself in the
out-stream. See the example given below:
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 cout << cout ;
return 0;
7 }
✌
✆
✞
0x6fefeb24
✌
✆
cout also concatenate the multi-line string or numbers, until an endl is not encountered.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
int x = 1;
7 cout << "x is : "; /* Label*/
cout << x; /* Integer value*/
9 cout << endl ;/* New line */
return 0;
11 }
✌
✆
✞
x is : 1
✌
✆
We can format the output by setting its width via width() function. It just created a
space, equals to its argument value and puts the contents from right align.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int i = 10;
cout . width(5); // Space for 5 characters
7 cout << i << " : ";
cout . width(8); // Space for 8 characters
9 cout << i * i << " n";
14. 14 Basic C++
return 0;
11 }
✌
✆
✞
10 : 100
✌
✆
It does nothing if width value is less than the size of succeeding output result.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int i = 10;
cout . width(5); /* Less than the succeeding output.*/
7 cout << "i is : " << i;
cout << "|";
9 cout . width(15) ; // Space for 15 characters
cout << "i*i is : " << i * i << "n";
11 return 0;
}
✌
✆
✞
i is : 10| i*i is : 100
✌
✆
fill() member function is used to fill the white spaces produced by width() function by
specific character. It is helpful in masking a value and indicating its actual size like
masking of phone number, credit card number etc.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 cout .fill (’@’);
int i = 10;
7 cout . width(5);/* less than the succeeding output.*/
cout << "i is : " << i;
9 cout << "|";
cout . width(15) ;
11 cout << "i*i is : " << i * i << "n";
return 0;
13 }
✌
✆
✞
i is : 10| @@@@@@i*i is : 100
✌
✆
We can set the precision limit by using precision() function. To set the precision for
output, we use syntax like
✞
1 cout .precision (<precision size >);
✌
✆
‘precision size’ tell the compiler to show the numerical output upto its size. See the
example below:
15. 1.1. INPUT/OUTPUT 15
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 cout . precision (15) ;
float i = 10.2;
7 cout << "i is : " << i << "n";
cout << "i*i is : " << i * i << "n";
9 return 0;
}
✌
✆
✞
i is : 10.1999998092651
i*i is : 104.039993286133
✌
✆
In above example, the float value 10.2 is converted into 15 precision digits. And actual
output is 10.1999998092651 which has 15 numeric digits excluding the decimal symbol
(.). setf () function is used to show the trailing zeros of the floating points upto default
precision size, i.e. 6.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
cout .setf (ios_base :: showpoint );
6 float i = 10.2;
cout << "i is : " << i << "n";
8 cout << "i*i is : " << i * i << "n";
return 0;
10 }
✌
✆
✞
i is : 10.2000
i*i is : 104.040
✌
✆
Other values of ios base are : ‘boolalpha’ flag for true and false values of inputs or
outputs. ‘showbase’ flag is used to prefix the (0 or 0x) on output. ‘showpoint’ flag is
used for showing trailing decimal points. ‘uppercase’ flag converts all alphabets into their
uppercase form. Hexadecimal form of output is represented by E notation. ‘showpos’
flag prefixes plus sign before positive numbers. ‘dec’ flag for base 10, ‘oct’ flag for base 8
and ‘hex’ flag for base 16 are used. ‘fixed’ flag is used for fixed-point notation, ‘scientific’
flag for scientific notation, ‘left’ flag for left-justification, ‘right’ flag for right-justification.
‘internal’ is lets the compiler to use the best way of output notation.
1.1.3 In Stream
cin is used to assign a value to a variable. It accepts the input from the in-stream and
assigns the value to succeeding variable. cin is always succeeded by >> symbol. It is
used as
16. 16 Basic C++
✞
cin >> <variable >
✌
✆
The iostream file defines cin as an object that represents this stream. For input, cin uses
the >> operator to extract characters from the input stream. Typically, you provide a
variable to the right of the operator to receive the extracted information.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
int x;
7 cin >> x;
cout << "x is : " << x; /* Integer value*/
9 cout << endl ; /* New line */
return 0;
11 }
✌
✆
✞
3
x is : 3
✌
✆
Strings or characters are placed in input stream by get object. get() object reads all
characters even if there are white spaces until it encounters null or EOF. Example is
given below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
char name [250];
6 cout << "Enter the name : ";
cin.get(name , 256) ;
8 cout << name ;
return 0;
10 }
✌
✆
✞
Enter the name : Arun
Arun
✌
✆
1.1.4 Error Stream
cerr is an error stream and part of the out-stream. We can add error instruction by using
this function as shown in the following example.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
17. 1.1. INPUT/OUTPUT 17
cerr << "Read error!!";
6 return 0;
}
✌
✆
✞
Read error!!
✌
✆
1.1.5 Log Stream
A program while it is compiled or while it is in run, suffers unexpected errors. It is good
habit of programming to place the errors and warning into a log file for future reference
and analysis. In C++, clog is an output stream which adds errors in error log.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 clog << "Read error!!";
return 0;
7 }
✌
✆
✞
Read error!!
✌
✆
1.1.6 End of Line
In C++, current line is terminated by using endl operator in out-stream. It is similar to
the literal ‘n’. These operators are also used to format outputs in C++.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 cout << endl ; /* First line break*/
cout << endl ; /* Second line break*/
7 cout << endl ; /* Third line break*/
return 0;
9 }
✌
✆
1.1.7 Null Char
If ends operator is added at the end of line, then this operator adds a null character at
the end of line. This operator terminates to the current line.
✞
1 #include <iostream >
#include <string >
3 using namespace std;
18. 18 Basic C++
5 int main (int argc , char ** argv ) {
string str = "This is test string.";
7 cout << str << ends ;
return 0;
9 }
✌
✆
✞
This is test string.
✌
✆
1.1.8 Flush
flush flushes the pending contents into the out-stream. This function works only with
out-stream.
✞
1 #include <ostream >
#include <fstream >
3 using namespace std;
5 int main (int argc , char *argv []) {
ofstream outfile("test .txt");
7 for (int n = 0; n < 100; n++)
outfile << n << flush;
9 outfile .close();
return 0;
11 }
✌
✆
1.1.9 Namespace
The namespace keyword is similar to class, struct, enum, and union. It puts the names
of its members in a distinct space. Creation of a new namespace is the only purpose
for namespace. Entities declared in a namespace-body are said to be members of the
namespace, and names, like variable, class, functions etc are said to be member names of
the namespace. We can create our own name space by declaration as given below:
✞
1 namespace <namespace name > {
<declarations >/<functions >/< statements >
3 }
✌
✆
namespaces are used as a mechanism for declaring same function multiple times so that
the function names couldn’t clash with each other. See the example below:
✞
1 #include <iostream >
using namespace std;
3 namespace My_NS {
int main (int argc , char *argv []);
5 }
7 int My_NS:: main (int argc , char *argv []) {
cout << 2;
19. 1.1. INPUT/OUTPUT 19
9 };
11 int main (int argc , char *argv []) {
return My_NS:: main (int argc , char *argv []);
13 }
✌
✆
✞
2
✌
✆
A namespace member is accessed by using ‘::’ (scope resolution) operator as shown in the
above example. A nested namescape can also be declared as accessed as shown below:
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
namespace A {
5 namespace N {
7 void f() {
cout << "Accessed .";
9 };
}
11 }
13 int main (int argc , char ** argv ) {
A::N::f();
15 return 0;
}
✌
✆
✞
Accessed .
✌
✆
In the above example, two namespaces are declared one inside the scope of other. Here,
scope of namespace N is inside the scope of namespace A. Function f() is inside the scope
of both namespaces. ‘::’ scope resolution operator is used to access the function f().
Function Namespace
A namespace member function can be accessed by using ‘::’ operator as shown below:
✞
1 <namespace name >::< member function >;
✌
✆
See the example below:
✞
1 #include <iostream >
using namespace std;
3
namespace myNameSpace1 {
5
void NoSpace () {
7 cout << "Space Not Available !!" << endl ;
}
20. 20 Basic C++
9 }
11 namespace myNameSpace2 {
13 void YesSpace () {
cout << "Space Available !!" << endl ;
15 }
}
17
int main (int argc , char *argv []) {
19
myNameSpace1 :: NoSpace ();
21 myNameSpace2 :: YesSpace ();
23 return 0;
}
✌
✆
✞
Space Not Available !!
Space Available !!
✌
✆
We can inject names at a time into the current scope with a using declaration. Unlike
the using directive, which treats names as if they were declared globally to the scope, a
using declaration is a declaration within the current scope.
✞
#include <iostream >
2 using namespace std;
4 namespace myNameSpace1 {
6 void NoSpace () {
cout << "Space Not Available !!" << endl ;
8 }
}
10
namespace myNameSpace2 {
12
void YesSpace () {
14 cout << "Space Available !!" << endl ;
}
16 }
18 /* Declaring myNameSpace1 to current scope.*/
using namespace myNameSpace1 ;
20
int main (int argc , char *argv []) {
22
NoSpace ();
24 // YesSpace () ;/* Not accessible .*/
26 return 0;
}
21. 1.1. INPUT/OUTPUT 21
✌
✆
✞
Space Not Available !!
✌
✆
A nested namespaces can be declared in current scope by using keyword as shown below:
✞
1 using namespace <parent namespace >::< child namespace >;
✌
✆
See the example below:
✞
1 #include <iostream >
using namespace std;
3
namespace myNameSpace1 {
5
void NoSpace () {
7 cout << "Space Not Available !!" << endl ;
}
9 namespace myNameSpace2 {
11 void YesSpace () {
cout << "Space Available !!" << endl ;
13 }
}
15 }
17 /* Declaring myNameSpace2 to current*
*scope. The member functions of *
19 *myNameSpace1 are not accessible . */
using namespace myNameSpace1 :: myNameSpace2 ;
21
int main (int argc , char *argv []) {
23
// NoSpace () ;/* Not accessible .*/
25 YesSpace ();
27 return 0;
}
✌
✆
✞
Space Available !!
✌
✆
A name space has following properties:
1. A namespace definition can appear only at global scope, or nested within another
namespace.
2. Termination colon does not require after closing braces.
3. A namespace definition can be “continued” over multiple header files.
4. A namespace name should be clear and readable.
5. We cannot create an instance of a namespace as we can do with a class.
22. 22 Basic C++
Class Namespace
When a user defines a class inside a namespace, then this user defined class is known as
class namespace. A user defined class inside class namespace is body of namespace. See
the example, below, in which class ‘Y’ is declared inside the namespace ‘X’.
✞
1 #include <iostream >
using namespace std;
3
namespace X {
5 class Y {/* class namespace */
public:
7 static int armLen; // Static data member
};
9 int i;
}
11 /* Initialize variable of class namespace . static*
*variable of class Y must be initialize here . */
13 int X::Y:: armLen = 10;
15 int main (int argc , char *argv []) {
/* Calling of class namespace .*/
17 cout << "Arm length is " << (X::Y:: armLen);
return 0;
19 }
✌
✆
✞
Arm length is 10
✌
✆
1.1.10 Escape Characters
Escape characters are used to perform action even if they are used as string. The escape
characters are n, t, a etc.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
int x;
7 cin >> x;
cout << "x is : nt" << x; /* New line and tab */
9 cout << endl ; /* New line */
return 0;
11 }
✌
✆
n adds a new line after “x is : ”. The output of the program is
✞
x is :
6
✌
✆
23. 1.2. MODIFIERS 23
The list of escape characters are explained in the following table:
Escape Character Meaning
t Adding a tab
n Start a new line
a Add CPU alert
b Backspace
f Form feed
r Carriage return
v Vertical tab
Backslash ()
’ Single quote (’)
" Double quote (”)
? Question mark (?)
1.2 Modifiers
A modifier is a function that tells how the value is printed in the output stream. For
example, the modifier ‘hex’ will cause the stream object to format subsequent integer
input to the stream in hexadecimal instead of decimal. Likewise, ‘oct’ results in integers
displaying in octal, and ‘dec’ reverts back to decimal.
✞
#include <iostream >
2 #include <iomanip >
using namespace std;
4
int main (int argc , char *argv []) {
6 cout << dec << 16 << ’ ’ << 10 << "n";
cout << oct << 16 << ’ ’ << 10 << "n";
8 cout << hex << 16 << ’ ’ << 10 << endl ;
return 0;
10 }
✌
✆
✞
16 10
20 12
10 a
✌
✆
Similarly, setw() sets the space either ‘left’ or ‘right’ by putting space columns.
✞
1 #include <iostream >
#include <iomanip >
3 using namespace std;
24. 24 Basic C++
5 int main (int argc , char *argv []) {
cout << setw (10) << right << 90 << setw (8) << "Help !n";
7 cout << setw (10) << left << 45 << setw (8) << "Hi!" << endl ;
return 0;
9 }
✌
✆
✞
90 Help !
45 Hi!
✌
✆
1.2.1 Quotes
Single quote is used to separate character value of a letter, digit and special characters.
Double quote is used to represent a string, like ”Hello, world.”. ‘A’ represents to the
character code ‘65’ while “A” is string.
✞
cout << ’A’ << endl ;/* char code of A*/
2 cout << "A" << endl ;/* String A*/
✌
✆
A character inside a single quote is char type data while a character inside double quote
is const char* type data.
1.2.2 Comments
Commenting is most useful feature of a programming language like, C, C++ etc. It is
used to write comments within or before or after a function or a variable. Stuff within the
commenting delimiters is ignored during compilation of the program. There are two type
of commenting delimiters. First, single line commenting delimiter and second, multi-
line commenting delimiter. For single line commenting ‘//’ is used and for multi-line
commenting ‘/* ... */’ is used.
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
int main (int argc , char ** argv ) {
6 int x;
cin >> x;
8 cout << "x is : nt" << x; // New line and tab
cout << endl ; /* New *
10 *line */
return 0;
12 }
✌
✆
The output of above program is
✞
x is :
6
✌
✆
25. 1.3. VARIABLES 25
1.3 Variables
Variables are the named labels which indicates the position where associated value is
stored. Variables are not values by itself but points to values. A variable is an address
of the stored value and it does not store value itself. A variable name should be valid,
readable and meaningful. Variable name should also be clear to identify easily while
scanning of a program from top to bottom.
1.3.1 Tokens
There are five kinds of tokens: identifiers, keywords, literals, operators, and other sepa-
rators. Blanks, horizontal and vertical tabs, new lines, form feeds and comments (collec-
tively, “white space”) are ignored except as they serve to separate tokens.
1.3.2 Address
A most commonly used word in C programming is ‘address’. By definition, “address” is
the location of memory where either data is stored or from where data is retrieved. An
address is a multibytes value that refers to a certain memory location rather than the
value stored at that location. Take a memory map of matrix 10 × 8 size as shown below:
11 12 13 14 15 16 17 18
21 22 23 24 25 26 27 28
31 32 33 34 35 36 37 38
41 42 43 44 45 46 47 48
51 52 53 54 55 56 57 58
61 62 63 64 65 66 67 68
71 72 73 74 75 76 77 78
81 82 83 84 85 86 87 88
91 92 93 94 95 96 97 98
101 102 103 104 105 106 107 108
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07
Low bytes
0x00
0x01
0x02
0x03
0x04
0x05
0x06
0x07
0x08
0x09
High
bytes
Here, memory addressed are two bytes long and it depends on system to system. The
first byte represents to high byte (i.e. rows in above matrix) and second byte represents
to low byte (i.e. column in the above matrix). For example an address 0×0304 (high byte
first and low byte thereafter) represents to the memory cell at 4th
row and 5th
column.
This value indicates to location of memory not to value at that location. From the above
matrix, at 4th
row and 5th
column cell, value stored is 45 not 0×0304 (address). In C we
do not deals directly with addresses but a variable name is assigned to the address. For
example, if a variable
✞
int i = 45;
✌
✆
26. 26 Basic C++
is declared and assigned a value equal to encircled value in above memory matrix. For
this value, address of variable ‘i’ shall be 0×0304. Address assigned to variable is always
hidden and can be retrieved by using addressof (‘&’) symbol.
✞
1 #include <iostream >
using namespace std;
3
int main () {
5 unsigned int i=45;
cout << &i;
7 return 0;
}
✌
✆
✞
0304
✌
✆
Here address variable is of 2 bytes long. A question rises here that why address is assigned
to a variable not the value itself. Its answer is, value assigned to variable is of any size and
for long values, it is impossible to assign directly to the variable. This is why, pointers or
variables are let to point the address the first byte of the memory location where data is
stored.
0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08 0x09
Low bytes
0x00
0x01
0x02
0x03
0x04
0x05
High
bytes
T w o P e n s 0
Str
Assume a variable ‘Str’ which is assigned a string “Two Pens”. This is eight bytes
long data. So a variable can not store this data directly. Therefore, the string is stored in
the temporary memory as shown in above figure. The variable ‘Str’ points to first byte
of the string, i.e. to ‘T’. The scope of ‘Str’ variable ended at the next null char ‘0’. The
memory address of ‘T’ is 0×0201. Hence, variable ‘Str’ points to memory address 0×0201
from where the string started not to the string.
1.3.3 Variables & Data-type
Variables are multi-character names used to refer to some locations in memory that holds
a value to which we are working. A variable is equivalent to its assigned value. A variable
may be alphanumeric name with underscore character. First numeric character in a
variable name is not acceptable. Use of spaces and special characters which are reserved
for internal use by C++ are illegal. Similarly, use of comma, dot, symbol of question
mark, symbols reserved for relation operations, symbols reserved for bitwise operations,
colon and line terminating symbol are also considered as illegal if used as a part of a
27. 1.3. VARIABLES 27
variable names. Key words specially reserved for internal programming of C++, can not
be used as variable name. A list of reserved keyword is given in section 5.3.1.
✞
1 int A1; // Legal and acceptable .
int 1A; // Illegal , first character is numeric
3 int A_1;// Legal , _ is acceptable
int A$1;// Legal , $ is not reserved character
5 int A#1;// Illegal , # reserved for header inclusion
int A 1;// Illegal , space is not acceptable
7 int for;// Illegal , for is reserved keyword
✌
✆
A variable declared once can not be declared again in the same scope. Multiple variables
of same data-type can be declared by using comma operator (,). To declare three integer
variables, the comma operator is used like
✞
1 int i; /* legal*/
int j; /* legal*/
3 int k; /* legal*/
/* Above three variables with comma operator */
5 int i, j, k; /* legal*/
int i=3, j, k; /* legal*/
✌
✆
See the example below, in which variable ‘i’ is declared twice in the same function and in
the same scope. This program shows compile time error.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
int i = 1; /* Declaration of i.*/
6 cout << i << endl ;
int i = 2; /* Redeclaration of i. It is illegal */
8 cout << i << endl ;
return 0;
10 }
✌
✆
✞
BUILD FAILED .......
✌
✆
Above example is rewritten as shown below, in which variable ‘i’ is declared twice in the
same function but in the different scope.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 int i = 1; /* Declaration of i in outer scope.*/
cout << i << endl ;
7 {/* Start of new inner scope block.*/
int i = 2; /* Redeclaration of i. It is legal*/
9 cout << i << endl ;
}
28. 28 Basic C++
11 return 0;
}
✌
✆
✞
1
2
✌
✆
Void
A variable or a function declared as void type, processes the statements/expressions
internally and does not return anything as a result. Inside the void type functions, new
variables/functions can be declared, modified or accessed but their values can not be
returned. Normally, all void type functions have no return keyword. If these function are
forced to return a value, a compile time error is thrown. Syntax of void type declaration
of function is given below:
✞
void myF() {}
✌
✆
Following code return a compile time error “error: return-statement with a value, in
function returning ‘void’”
✞
1 #include <iostream >
using namespace std;
3
void myF(int i) {
5 return i;
}
7
int main (int argc , char ** argv ) {
9 myF (10) ;
return 0;
11 }
✌
✆
But the void type function can put the result in out stream as shown in the following
example.
✞
1 #include <iostream >
using namespace std;
3
void myF(int i) {
5 cout << i;
}
7
int main (int argc , char ** argv ) {
9 myF (10) ;
return 0;
11 }
✌
✆
✞
10
✌
✆
29. 1.3. VARIABLES 29
Character
char is used to declare and initialize a character or a group of characters as string.
Character string can be initialized as an array or pointer. The size of char data-type is
1 byte. By default, a char is signed unless unsigned keyword is not used. string type
cast is also available under the string header file and an array can be initialized by using
string type cast.
✞
1 char <var name >=’<single character >’;
char <var name >[]= "<long string >";
3 string <var name >="<long string >";
✌
✆
A char variable without initialization stores null character. A single characcter should
be inside single quote.
✞
1 #include <iostream >
#include <string >
3 using namespace std;
5 int main (int argc , char ** argv ) {
char ch = ’T’;
7 cout << "Character is " << ch << endl ;
return 0;
9 }
✌
✆
✞
Character is T
✌
✆
A string can be initialized as an array as well as a string. The string is put in the output
stream directly as shown in the example given below:
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
char str[] = "Alora caves are in India.";
7 string str2 = "Swaminathan temple.";
cout << str << endl ;
9 cout << str2 << endl ;
return 0;
11 }
✌
✆
✞
Alora caves are in India.
Swaminathan temple.
✌
✆
See another example, in which character array is initialized with empty string (NOT
NULL).
✞
#include <iostream >
2 using namespace std;
30. 30 Basic C++
4 int main (int argc , char ** argv ) {
char str [5]; /* Empty and NULL .*/
6 cout << "String is : ";
cout << str << endl ;
8 string str2 = ""; /* Empty but NOT NULL .*/
cout << "Second string is : ";
10 cout << str2 << endl ;
return 0;
12 }
✌
✆
✞
String is : (null )
Second string is :
✌
✆
Integer
A 4 bytes long numerical value is declared and initialized by using data-type int. If an
integer variable is initialized a decimal number with fraction part, then its fraction part
is truncated. A valid integer type is either a whole number or a whole number ended
with ‘L’. An integer variable is declared and initialized as shown below:
✞
int <var name >; /* Declared .*/
2 int <var name >=<value >; /* Initialized .*/
✌
✆
The initialization of float type numeric value to an integer type variable is illegal.
✞
int i=2; /* Legal*/
2 int j=2.1;/* Illegal */
✌
✆
There are two types of initialization, (i) direct initialization and (ii) copy initialization.
Direction intialization is compatible with C++11 and new standards.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
int l {10}; // Direct initialization
6 cout << l << "n";
int m = {10}; // Copy initialization
8 cout << m << "n";
return 0;
10 }
✌
✆
✞
10
10
✌
✆
An example is given below:
31. 1.3. VARIABLES 31
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
int main (int argc , char ** argv ) {
6 int x = 5;
cout << x; /* Integer value*/
8 cout << endl ; /* New line */
return 0;
10 }
✌
✆
✞
5
✌
✆
When a float type number is assigned to an integer type variable then the decimal part
of the float number is truncated. Remember that, float numbers whose size is larger than
size of integer, cause overflow.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
float a = 5.54;
7 int b = a;
float c = 5.54;
9 int d = c;
cout << "a = " << a << endl ; /* Float value*/
11 cout << "b = " << b << endl ; /* Integer value*/
cout << "c = " << c << endl ; /* Float value*/
13 cout << "d = " << d << endl ; /* Integer value*/
return 0;
15 }
✌
✆
✞
a = 5.54
b = 5
c = 5.54
d = 5
✌
✆
We can also convert a float value into an integer value by using the syntax as given below:
✞
double i=3.548751;
2 int j = int (i);
✌
✆
Example for this syntax is given below:
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
32. 32 Basic C++
int main (int argc , char ** argv ) {
6 float a = 5.54874;
int b = int(a);
8 cout << "a = " << a << endl ; /* Float value*/
cout << "b = " << b << endl ; /* Integer value*/
10 return 0;
}
✌
✆
✞
a = 5.54874
b = 5
✌
✆
An integer variable assigned a value started with ‘0’ is taken as octal format by the C++
compiler. See the example below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
int i = 01000;
6 cout << i << endl ;
return 0;
8 }
✌
✆
✞
512
✌
✆
In C++, it is extensibility that, we can either pass the address of a variable to the function
argument as pointer or we can catch address of a variable through function parameter by
using ‘&’ operator. See the example below:
✞
1 #include <iostream >
using namespace std;
3
/* Catch address of variable b and *
5 *address of variable c through its pointer */
void myF(int a, int &b, int *c){
7 a = a*2;
b = b + 10;
9 *c = *c + 1;
}
11
int main (){
13 int a = 1, b=3, c = 5;
myF(a, b, &c);
15 printf("%d, %d, %d",a, b, c);
return 0;
17 }
✌
✆
✞
1, 13, 6
✌
✆
33. 1.3. VARIABLES 33
Float Points
A float or a double has three components, (i) a sign bit, (ii) exponent and (iii) mantissa.
A floating point number is written as
f = ±m × b±e
Here, m is mantissa of the number, b is base, i.e. 2 in IEEE-754 standards. e is exponent
of the floating point number. In this section we shall use single point (float) floating
numbers. A float datatype number is 32 bits long and has three components, (i) a sign
bit (first bit from left side), (ii) an exponent (next 8 bits from left side) and (iii) a mantissa
(rest of 23 bits). The exponent is an excess-127 binary notation. This binary number
is also known as exponent bias.
Binary Equivalent Desired Exponent
· · · · · ·
01111100 -3
01111101 -2
01111110 -1
01111111 0
10000000 1
10000001 2
10000010 3
· · · · · ·
In this notation, binary number 01111111, equivalent to decimal 127 is a binary ex-
ponent equivalent to decimal 0. The next binary exponent i.e. sum of binary 01111111
and bit 1 represents to exponent equivalent to decimal 1 (equivalent to binary 10000000).
Similarly, subtraction of bit 1 from 01111111 represents to exponent equivalent to deci-
mal −1 (equivalent to binary 01111110). Remember that for binary equivalent form of
floating point numbers, base is 2, i.e. exponent binary 01111111 is equal to in decimal
form of 20
, exponent binary 10000000 means 21
, exponent binary 01111110 means 2−1
and so on.
125 126 127 128 129
01111101 01111110 01111111 10000000 10000001
−2 −1 0 1 2
2−2
2−1
20
21
22
Decimals
Excess-127
e-Line
2e
Value
34. 34 Basic C++
The decimal exponent equivalent to binary exponent is obtained by subtracting 01111111
from the given binary exponent. The mantissa binary numbers are solved from left side
to right side. Here, we are dealing with binary fractions, so the leftmost mantissa bit
means 2−1
, the next right bit has meaning of 2−2
and so on. The place values of mantissa
bits from left side to right side are 2−1
, 2−2
, 2−3
etc. The first bit of a non-zero binary
significand is always 1. Hence mantissa is given by
M = 1 +
n
X
i=1
biti × 2−i
Here, i is ith
bit counted from left hand side to right hand side in mantissa part. n is
total number of significant digits in mantissa.
Illustrated Example Assume a floating point representation ‘0 0111 1100 0000 0000
0000 0000 0000 000’ shown in binary form. The sign bit of this binary number is ‘0’,
hence it is positive value. The exponent binary number is 01111100 and mantissa number
is 0000 0000 0000 0000 0000 000. Note that if left most digit of the binary exponent part
of floating point number is ‘0’, then exponent is obtained by subtracting 01111111 from
the given binary exponent. Here, binary subtraction of
01111100
-01111111
-00000011
which is equivalent to decimal −3. The exponent value is −3. The mantissa part is
all zero, hence
M = 1 +
23
X
i=1
biti × 2−i
gives mantissa ‘1’. Now, the number is
r = 1 × 2−3
It gives 0.125.
Illustrated Example Assume a floating point representation ‘0 1010 0110 1101 0001
1010 1001 0100 101’ shown in binary form. The sign bit of this binary number is ‘0’,
hence it is positive value. The exponent binary number is 10100110 and mantissa number
is 1101 0001 1010 1001 0100 101. Note that, if the left most digit is of binary exponent is
‘1’, then exponent is obtained by subtracting 01111111 from the given binary exponent.
Here, binary subtraction of
10100110
-01111111
00100111
35. 1.3. VARIABLES 35
which is equivalent to decimal 39. The exponent value is 39. The mantissa part is
M = 1 +
23
X
n
bitn × 2−n
gives mantissa ‘1.818989396095270’. Now, the number is
r = 1.818989396095270 × 239
It gives 999999995904.
Float Decimals
This data-type is floating-point type. It usually referred to as a single-precision floating-
point. Float-to-integer or integer-to-float type conversion of numbers take place by as-
signing float variable to integer variable and integer variable to float variable respectively.
It is 4 byte long. Its range is from 1.2 × 10−38
to 1.2 × 1038
. The precision of the float
data-type is upto 6 decimal places. Syntax for the float data-type is
✞
1 float <var name >;
float <var name >=< decimal value >;
✌
✆
See the example below.
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
int main (int argc , char ** argv ) {
6 float i = 10.25;
int iF = i;
8 int j = 15;
cout << "i as float : ";
10 cout << i << endl ;
cout << "i as integer : ";
12 cout << iF << endl ;
cout << "Int j as float : ";
14 float jF = j;
cout << jF << endl ;
16 return 0;
}
✌
✆
✞
i as float : 10.25
i as integer : 10
Int j as float : 15
✌
✆
36. 36 Basic C++
Long Decimals
long is long integer type. It is capable of containing any integer value within the range
from 2147483647 to +2147483647. It is a 32 bits or 4 bytes long in size. Long-to-integer
or integer-to-long type conversion of numbers is done by type casting.
✞
1 long <var name >;
long <var name >=< decimal value >;
✌
✆
See the example below.
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char ** argv ) {
long i = 10.25;
6 int j = 15;
cout << "i as long : " << i << endl ;
8 cout << "i as integer : " << (int) i << endl ;
cout << "Integer j as long : " << (long ) j << endl ;
10 return 0;
}
✌
✆
✞
i as long : 10
i as integer : 10
Int j as long : 15
✌
✆
Double
It is 8 bytes long data-type. long double is also a 8 byte long data type. Syntax for the
double data-type is
✞
1 double <var name >;
double <var name >=< decimal value >;
✌
✆
See the example for long data type, which is given below:
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
int main (int argc , char ** argv ) {
6 double i = 10.25;
cout << "i as double : ";
8 cout << i << endl ;
return 0;
10 }
✌
✆
✞
i as double : 10.25
✌
✆
37. 1.3. VARIABLES 37
As we know that an integer is a zero precision value. This is why
✞
1 int i=1.1;
✌
✆
is not legal. C++ truncates the decimal part to convert a float value into the integer
value. Action of rounding off to a decimal number into a whole integer is not performed.
Similarly
✞
1 double j=1;
✌
✆
is also not legal because double is floating point precision value. Yet the C++ tries to
convert it into a double value. A practical problem occurs when we tries to divided
integers and tried to return a double value as shown below:
✞
1 double l=2/3;
✌
✆
The result will not be 0.666666 but it will be 0.0, because division of integers is considered
as integer. This is why, 0.666666 will be converted into integer 0 and then double will
convert it into float value 0.0. This is the reason that, why should we need the same
division be in the form of
✞
1 double l=2.0/3.0;
✌
✆
See the example given below:
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
double i = 10.25;
7 cout << "i as double : ";
cout << i << endl ;
9 double j = 1 / 3;
cout << "j as double : ";
11 cout << j << endl ;
double k = 2.0 / 3.0;
13 cout << "k as double : ";
cout << k << endl ;
15 return 0;
}
✌
✆
✞
i as double : 10.25
j as double : 0
k as double : 0.666666
✌
✆
We can change the precision of the decimal part of a real number by setting precision
counts by using setprecision() function. This function requires ‘iomanip’ header file. Its
syntax is
38. 38 Basic C++
✞
1 setprecision (<precision places >);
✌
✆
See the example below:
✞
1 #include <iostream >
#include <iomanip >
3 using namespace std;
5 int main (int argc , char ** argv ) {
double i = 123.123456789;
7 cout << "1 precision points : " << setprecision (1) << i << endl ;
cout << "2 precision points : " << setprecision (2) << i << endl ;
9 cout << "3 precision points : " << setprecision (3) << i << endl ;
cout << "4 precision points : " << setprecision (4) << i << endl ;
11 cout << "5 precision points : " << setprecision (5) << i << endl ;
return 0;
13 }
✌
✆
✞
1 precision points : 1e+02
2 precision points : 1.2e+02
3 precision points : 123
4 precision points : 123.1
5 precision points : 123.12
✌
✆
The precision are classified as
1. fixed This precision operator returns the floating-point values in fixed-point nota-
tion.
2. scientific This precision operator writes the floating-point values in scientific nota-
tion.
3. hexfloat This precision operator writes the floating-point values in hexadecimal
format.
Example of scientific floating point type:
✞
1 #include <iostream >
#include <iomanip >
3 using namespace std;
5 int main (int argc , char ** argv ) {
double i = 123.123456789;
7 cout << "i is " << i << endl ;
cout << "Scientific floating point type :" << scientific <<
endl ;
9 cout << "1 precision points : " << setprecision (0) << i << endl ;
cout << "2 precision points : " << setprecision (2) << i << endl ;
11 cout << "3 precision points : " << setprecision (3) << i << endl ;
39. 1.3. VARIABLES 39
cout << "4 precision points : " << setprecision (4) << i << endl ;
13 cout << "5 precision points : " << setprecision (5) << i << endl ;
return 0;
15 }
✌
✆
✞
i is 123.123456789
Default floating point type :
1 precision points : 1e+02
2 precision points : 1.23 e+02
3 precision points : 1.231e+02
4 precision points : 1.2312e+02
5 precision points : 1.23123 e+02
✌
✆
Example of fixed floating point type:
✞
1 #include <iostream >
#include <iomanip >
3 using namespace std;
5 int main (int argc , char ** argv ) {
double i = 123.457;
7 cout << "i is " << i << endl ;
cout << "Fixed floating point type :" << fixed << endl ;
9 cout << "1 precision points : " << setprecision (0) << i << endl ;
cout << "2 precision points : " << setprecision (2) << i << endl ;
11 cout << "3 precision points : " << setprecision (3) << i << endl ;
cout << "4 precision points : " << setprecision (4) << i << endl ;
13 cout << "5 precision points : " << setprecision (5) << i << endl ;
return 0;
15 }
✌
✆
✞
i is 123.457
Fixed floating point type :
1 precision points : 123
2 precision points : 123.46
3 precision points : 123.457
4 precision points : 123.4570
5 precision points : 123.45700
✌
✆
Boolean
C++ has boolean data type. If a variable is set as boolean true, then it returns 1.
Similarly, if the variable is set as boolean false, then it returns 0.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 bool i = true ;
40. 40 Basic C++
bool j = false;
7 cout << "i is : ";
cout << i << endl ;
9 cout << "j is : ";
cout << j << endl ;
11 return 0;
}
✌
✆
✞
i is : 1
j is : 0
✌
✆
Reference of Variables
A reference to an existing variable is its alias/synonym name. It refers to an address. An
alias variable is declared as shown below:
✞
int i = 15; // i is a variable
2 int &k = i; // k is a reference to i
const int &l = 5; // l is a reference to constat value
4 const int &m = i; // m is a reference to constant i
✌
✆
See the example below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
int i = 15; // i is a variable
6 int &j = i; // k is a reference to i, i.e. alias name
cout << "i : " << i << ", j : " << j << endl ;
8 cout << "&i : " << &i << ", &j : " << &j << endl ;
return 0;
10 }
✌
✆
✞
i : 15, j : 15
&i : 0x22 ff48, &j : 0x22 ff48
✌
✆
While declaring a reference, it can not refer to a NULL value or to constant value as
non-constant reference. For example,
✞
int &i; // Results compile time error
2 int &j = 5; // invalid initialization of non -const reference
// compile time error
✌
✆
A reference is always fixed. If it is referred, then it can not be re-reference. For example,
✞
1 int a, b, &c = a;// c is reference to a
&c = a; // Trying again , c is reference to a
3 // results compile time error
✌
✆
41. 1.3. VARIABLES 41
Reference is not allowed for arrays.
Constant Data Type
const is used to declare a variable as a constant data type. Syntax for it is
✞
1 const int i;
✌
✆
It is highly recommended to use const qualifier for a variable if the variable holds a large
value. If a variable with large value is modified then there are chances of overflow of a
variable value. Similarly a function can also be restricted to constant return type.
✞
1 const int f();
✌
✆
In the following example, an integer variable i is declared as constant. When we try to
increase its value by one using increment operator, compiler throws error that we are
trying to increase a value of readonly variable.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char *argv []) {
5 const int i = 10;
cout << "i is " << i << endl ;
7 //i++;/* Will show error that variabl is readonly */
// cout << "i is " << i << endl ;
9 return 0;
}
✌
✆
✞
i is 10
✌
✆
constexpr are those expressions which are evaluated at compile time. It is used as
✞
1 const int v = 17;
constexpr double m = 1.4* v; /* v must be a constant */
✌
✆
Data Type Definition
typedef is used to create an alias name for any other data-type. As such, it is often
used to simplify the syntax of declaring complex data structures consisting of struct and
union types, but is just as common in providing specific descriptive type names for integer
data-types of varying lengths. The syntax of typedef is given by
✞
typedef <old type name > <new alias >;
✌
✆
Redefining the long long data type with new variable as given below.
✞
1 typedef long long <major unit >;
typedef int <minor unit >;
✌
✆
42. 42 Basic C++
An example is given below.
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4 typedef long long km;
6 int main (int argc , char ** argv ) {
km dis = 10;
8 cout << "Distance is " << dis <<" km.";
return 0;
10 }
✌
✆
✞
Distance is 10 km.
✌
✆
Declaration, Initialization & Assignment
A declaration is a definition unless it declares a function without specifying the function’s
body. For example, declaration with keywords like extern, struct, namespace, enum,
typedef, using and function with statements are just definitions not declarations.
✞
1 extern const int c = 1; // defines c
int f(int x) { return x+a; } // defines f and defines x
3 struct S { int a; int b; }; // defines S, S::a, and S::b
enum { up , down }; // defines up and down
5 namespace N { int d; } // defines N and N::d
✌
✆
Same keywords as given above without statements are just declarations.
✞
1 extern int a; // declares a
extern const int c; // declares c
3 int f(int); // declares f
struct S; // declares S
5 typedef int Int; // declares Int
extern X anotherX ; // declares anotherX
7 using N::d; // declares d
✌
✆
The point of declaration for a variable is immediately after its complete declarator and
before its initializer (if any). A variable in C++ can be assigned as integer, if syntax is
defined as given below:
✞
1 int variable_name ;
✌
✆
It means there is some space declared somewhere to store integer value. Multiple variables
can be assigned in single line or successive way like
✞
1 int variable_a , variable_b , variable_c ;
✌
✆
A variable in C++ is said to be initialized if a numeric or an alphabetic value is assigned
to it. For example variable a is initialized by
43. 1.3. VARIABLES 43
✞
1 int variable_a = <value >;
✌
✆
To distinct the words of a variable, underscore symbol (‘ ’) is used. Anytime within a
program in which we specify a value explicitly instead of referring to a variable or some
other form of data, that value is referred as a literal. Literals can either take a form
defined by their type, or one can use hexadecimal (hex) notation to directly insert data
into a variable regardless of its type. Hex numbers are always preceded with ‘0x’.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 const int v = 0x15;
cout << "v is : ";
7 cout << v << endl ;
return 0;
9 }
✌
✆
✞
v is 21
✌
✆
Another example for same purpose with different procedure.
✞
1 #include <iostream >
#define CNT(x, y) x##y
3 using namespace std;
5 int main (int argc , char ** argv ) {
const int v = CNT(0x, 12345);
7 cout << "v is : ";
cout << v << endl ;
9 return 0;
}
✌
✆
✞
v is : 74565
✌
✆
There are five major data-types which are given in the following table. C++ also allow
suitable combinations of numeric data types for long numerical values.
Datatype Meaning
int Integer
char Character
long Long integer
float Floating data with single digit precision
double Floating data with double digit precision
44. 44 Basic C++
The length of data-type is measured its byte length. The data-type may be signed or
unsigned. In signed data-type, the MSB is used for sign declaration and rest of the bits
are used for data value. In unsigned data-type, all the bits are used for data value. The
byte length of different data-type are given in following table.
Type Storage size
char 1 byte
un-signed char 1 byte
signed char 1 byte
int 2 or 4 bytes
unsigned int 2 or 4 bytes
unsigned short 2 bytes
short 2 bytes
long 4 bytes
unsigned long 4 bytes
long long 8 bytes
long long int 8 bytes
unsigned long long 8 bytes
double 8 bytes
long double 10 bytes
Table 1.1: Declaration type and their storage size in byte.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
typedef long double km;
5
int main (int argc , char ** argv ) {
7 km dis = 10.5;
cout << "Distance is " << dis <<" km.";
9 return 0;
}
✌
✆
✞
Distance is 10.5 km.
✌
✆
If variables are not initialized then they give strange result.
✞
1 #include <cstdlib >
#include <iostream >
45. 1.3. VARIABLES 45
3 using namespace std;
5 int main (int argc , char ** argv ) {
int dis;
7 cout << "Distance is " << dis <<" km.";
return 0;
9 }
✌
✆
✞
Distance is -1218502656 km.
✌
✆
Numerical Variable Conversion
Variable of int type stores data with zero digit precision while ‘float’ stores data with
single digit precision. When float type number is assigned to the integer type variable
then only whole part of the number is assigned to the integer variable and its fraction
part is truncated. See the example below.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
float mm =10.58;
7 int dis=mm;
cout << "mm is " << mm <<"n";
9 cout << "dis is " << dis <<"n";
return 0;
11 }
✌
✆
The output of this program is
✞
mm is 10.58
dis is 10
✌
✆
Signed & Unsigned Integer
A byte is 8 bit long. The size of int is 4 bytes, i.e. 32 bits. A signed integer is integer whose
last bit counted from right to left, i.e. MSB is taken as sign bit. If integer is declared as
signed then MSB is sign bit and remaining 31 bits are used for storing integer. If integer
is declared as unsigned then all 32 bits are used for storing integer.
✞
//+--------------------- Sign bit
2 (1) 1111111 b =>-127 d // Signed 7 bit integer
11111111 b => 255d // Unsigned 8 bit integer
✌
✆
A signed integer ranges from -2147483647 to 2147483647 while unsigned integer ranges
from 0 to 4294967294. In the C++, bit ‘0’ is used as positive sign and bit ‘1’ is used
as negative sign. Now, a question is rises that what will happen if we store a negative
number to the unsigned variable? For example,
46. 46 Basic C++
✞
1 unsigned char i=-16; // char type for one byte long data
✌
✆
The answer is that, here, compiler uses one’s complement method to store the negative
value. It means first, 16 is converted into binary data and then it is complemented and
added by bit 1. The result thus obtained is stored in the memory address pointed by the
variable.
1 Byte
0 0 0 1 0 0 0 0 = 1610
1 Byte
1 1 1 0 1 1 1 1 = 23910
Complement
1 Byte
1 1 1 1 0 0 0 0 = 24010
Complement + 1
Now, an unsigned variable (one byte long here) stores value -16 in memory as binary
11110000b. See the example given below:
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main () {
unsigned char c = -16;
7 cout << (int) c << endl ;
return 0;
9 }
✌
✆
✞
240
✌
✆
Overflow of Data
A variable declared as integer, long, float or double integer and character has capacity
to store a specific size of data. An integer variable can not store data as long as float
variable. This is why, a variable shall be declared in proper size for storing a data. To
understand the overflow, consider a virtual data-type that can store only one byte long
data. This data-type may be signed or unsigned. First assume it is unsigned, then the
largest decimal value, that can be stored by it is 255. Initially, data-type has initialized
with decimal value 254.
✞
1 data -type k = 254d = 11111110 b
✌
✆
data-type is incremented by 1, it becomes
47. 1.3. VARIABLES 47
✞
1 data -type k = 255d = 11111111 b
✌
✆
Again, data-type is incremented by 1, it becomes
✞
1 data -type k = 255d = 1 00000000 b
✌
✆
The size of result is larger than one byte. The value of data-type reset to zero due to
overflow. Here, overflow carry is ‘1’. Similarly a positive signed value becomes negative
signed value if it is incremented beyond the signed data range. Taking the same data-type
with signed value.
✞
1 /* Bit inside parentheses represents to sign .*/
data -type k = 127d = (0) 1111111b
✌
✆
It is incremented by 1, it becomes
✞
/* Bit inside parentheses represents to sign .*/
2 data -type k = -0d = (1) 0000000 b
✌
✆
It becomes negative zero. Again, if increment by 1, the result is
✞
/* Bit inside parentheses represents to sign .*/
2 data -type k = -1d = (1) 0000001 b
✌
✆
Which is -1. Here, again data-type variable is overflowed. In the following example result
is not as required due to bigger size of data than the integer variable can store. An integer
can store 2 or 4 byte long data. In numerical equivalent the maximum unsigned number
can be stored by an integer variable is ‘2147483647’. If number is larger than it, the result
is wiered.
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
int main (int argc , char ** argv ) {
6 /* Signed value of an integer ranges *
* from -2147483648 to 2147483647. If *
8 * integer value become larger than *
* 2147483647 it overflows by one bit *
10 * and integer value becomes largest *
* negative number. */
12 signed int i = 2147483645;
int j;
14 for (j = 0; j < 5; j++)
cout << i + j << "n";
16 return 0;
}
✌
✆
48. 48 Basic C++
✞
2147483645
2147483646
2147483647
-2147483648
-2147483647
✌
✆
Size of Memory Used (sizeof)
sizeof operator is used to find the size of used memory. Its result is an implementation
defined, and will be either unsigned long or unsigned int. A working example is
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char ** argv ) {
int *a;
7 cout << "Storage size for a : " << sizeof (a) << endl ;
int *b[10];
9 cout << "Storage size for b : " << sizeof (b) << endl ;
int *c[20];
11 cout << "Storage size for c : " << sizeof (c) << endl ;
int *d[30];
13 cout << "Storage size for d : " << sizeof (d) << endl ;
return 0;
15 }
✌
✆
The output is
✞
Storage size of a : 4
Storage size of b : 40
Storage size of c : 80
Storage size of d : 120
✌
✆
When sizeof is used to get the size of an array it returns one more the actual size of
array (number of characters and followed by null). It always returns ‘1’ if its argument
is a pointer.
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
const char arr[] = "Hello";
6 const char *cp = "Hello";
8 int main (int argc , char *argv []) {
cout << "Size of array " << (unsigned long ) sizeof (arr) <<
endl ;
10 cout << "Size of *cp " << (unsigned long ) sizeof (*cp) << endl ;
49. 1.3. VARIABLES 49
return 0;
12 }
✌
✆
✞
Size of array 6
Size of *cp 1
✌
✆
Here is another example.
✞
#include <cstdlib >
2 #include <iostream >
using namespace std;
4
const char *list [] = {"Red", "Green", "Blue ", "Black", "White"};
6 #define LIST_SIZE (sizeof(list )/sizeof(list [0]) )
8 int main (int argc , char *argv []) {
int ix;
10 for (ix = 0; ix < LIST_SIZE ; ix ++) {
cout << list [ix] << endl ;
12 }
return 0;
14 }
✌
✆
✞
Red
Green
Blue
Black
White
✌
✆
Default Casting
C++ is a smart language. When the value of a variable is put in output stream, it
automatically check that which type of the value is to be placed at output stream. When
a float variable is assigned to the integer variable, C++ automatically truncate to the
decimal part.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char *argv []) {
float iA = 10.25;
7 int iB = iA;
cout << "iA is " << iA << endl ;
9 cout << "iB is " << iB << endl ;
return 0;
11 }
✌
✆
50. 50 Basic C++
✞
iA is 10.25
iB is 10
✌
✆
C++ also support C like casting of data type. In the following example, integer and float
values are casted as float and integer type respectively.
✞
#include <string >
2 #include <iostream >
using namespace std;
4
int main (int argc , char *argv []) {
6 int i = 10;
float j = 15.12547;
8 cout << "i is " << i << "n";
cout << "Float of i is " << (float) i << "n";
10 cout << "j is " << j << "n";
cout << "Integer of j is " << (int) j << "n";
12 return 0;
}
✌
✆
✞
i is 10
Float of i is 10
j is 15.1255
Integer of j is 15
✌
✆
Another example
✞
#include <string >
2 #include <iostream >
using namespace std;
4
int main (int argc , char *argv []) {
6 int i = 90;
cout << "i is " << i << "n";
8 cout << "Character of i is " << (char ) i << "n";
return 0;
10 }
✌
✆
✞
i is 90
Character of i is Z
✌
✆
1.3.4 Scope of Variables
The point of declaration for a name is immediately after its complete declarator and
before its initializer.
✞
int x = 12; // Point of declaration of variable x
✌
✆
51. 1.3. VARIABLES 51
A variable, that is valid only within some possibly discontiguous portion of program text
(program texts within {...}) called its scope. The variable which is declared is valid within
its scope except that if it is not declared as friend variable in case of a class variable.
1.3.5 Qualifiers
Qualifiers are those operators which restrict the scope of a variable. There are const,
static, extern, volatile, auto and register type qualifiers.
const Qualifier
The const qualifier is used with a variable to make it a constant or parameter. The value
of const type variable does not allowed to be changed later. const declaration creates the
declared variable as readonly. The method of const declaration is
✞
1 const int i = 12; // OK
✌
✆
Remember that it is not allowed to declare const as given below.
✞
1 const int i;
i=12; // Not OK
✌
✆
An array can also be declared const that can not be altered later. For example
✞
const int mdays[12] = {31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31};
✌
✆
A pointer can also be declared as constant.
✞
1 const float * ptrf ; /* ptrf points to a constant float value */
✌
✆
In following example, i is declared as constant integer equal to 10. It is printed int the
output console.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 /* Declare i as constant integer .*
* And initialize it at here . */
7 const int i = 10;
cout << "i is " << i << endl ;
9 return 0;
}
✌
✆
✞
i is 10
✌
✆
But changing the value of variable i is not allowed. In following example, compiler shows
error at i++;
52. 52 Basic C++
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
5 /* Declare i as constant integer .*
* And initialize it at here . */
7 const int i = 10;
cout << "i is " << i << endl ;
9 /* Increment of i is not allowed.*/
i++; /* Illegar expression . Will show error.*/
11 cout << "i++ is " << i << endl ;
return 0;
13 }
✌
✆
In case of classes, if a member function is declared as a constant member function, then
the value of data member can be changed.
static Qualifier
When we declare a function or global variable as static it becomes internal. We cannot
access the function or variable through the extern keyword from other files. When we
declare a local variable as static, it is created just like any other variable. However, when
the variable goes out of scope the variable stays in memory, retaining its value, until the
program ends. Variables declared static are initialized to zero (or for pointers, NULL) by
default.
✞
1 #include <iostream >
using namespace std;
3
/* This variable is accessed by both up() and down () functions .*/
5 static int j = 0;
7 void up(void ) {
/*k is set to 0 when the program starts. The line *
9 *is then "ignored" for the rest of the program . *
*(k is not set to 0 every time up() is called) */
11 static int k = 0;
j++;
13 k++;
cout << "up() called. k= " << k << ", j= " << j << "n";
15 }
17 void down (void ) {
static int k = 0;
19 j--;
k--;
21 cout << "down () called. k= " << k << ", j= " << j << "n";
}
23
int main (int argc , char ** argv ) {
53. 1.3. VARIABLES 53
25 int i;
/* Call up function 3 times , then down function 2 times*/
27 for (i = 0; i < 3; i++)
up ();
29 for (i = 0; i < 2; i++)
down ();
31 return 0;
}
✌
✆
Output of above function is
✞
up() called. k=1, j=1
up() called. k=2, j=2
up() called. k=3, j=3
down () called. k=-1, j=-2
down () called. k=-2, j=1
✌
✆
The ‘j’ variable is accessible by both up and down and retains its value. The ‘k’
variables also retain their value, but they are two different variables, one in each of their
scopes. Static variables are a good way to implement encapsulation.
Property Default Value
Keyword used static
Storage Memory
Default value Zero
Scope Local to the block in which it is declared
Lifetime Value persists between different function calls
Keyword optionality Mandatory to use the keyword
Table 1.2: Features of static variable.
Static variable initialized once can not be initialized again but the variable can store
new value.
✞
1 #include <iostream >
using namespace std;
3
void print(void ) {
5 /* Static initialization */
static int a = 0;
7 cout << a << endl ;
/* Increment of the static value*/
9 a++;
}
11
int main (int argc , char ** argv ) {
13 print();
54. 54 Basic C++
print();
15 print();
return 0;
17 }
✌
✆
✞
0
1
2
✌
✆
extern Qualifier
extern is used when a file needs to access a variable in another file that it may not have
#include directly. Therefore, extern does not actually carve out space for a new variable,
it just provides the compiler with sufficient information to access the remote variable. It
also makes a variable global.
Property Default Value
Keyword used extern
Storage Memory
Default value Zero
Scope Global (all over the program)
Lifetime Value persists till the program’s execution comes to an end
Keyword optionality Optional if declared outside all the functions
Table 1.3: Features of extern variable.
The syntax of this qualifier is
✞
1 /* implicit declaration of variable , this only describes and *
* assumes allocated elsewhere , normally from include */
3 extern int AVar ;
/* Custom function that will increase external variable by one*/
5 void MyFunc(void ) {
++ AVar ;
7 }
✌
✆
A complete example is given below:
✞
1 #include <iostream >
using namespace std;
3
int units = 0;
5 /* an external variable */
void Reply(void );
7
55. 1.3. VARIABLES 55
int main (int argc , char ** argv ) {
9 extern int units; /* an optional redeclaration */
cout << "How many units?n";
11 cin >> units;
while (units != 5)
13 Reply();
cout << "Look it !!!!n";
15 return 0;
}
17
void Reply(void ) {
19 /* optional redeclaration omitted */
cout << "Try again.n";
21 cin >> units;
}
✌
✆
✞
How many units?
3
Try again.
5
Look it !!!!
✌
✆
volatile Qualifier
volatile is a special type modifier which informs the compiler that the value of the variable
may be changed by external entities other than the program itself. This is necessary
for certain programs compiled with optimization, if a variable was not defined volatile
then the compiler may assume that certain operations involving the variable are safe to
optimize away when in fact they aren’t. volatile is particularly relevant when working
with embedded systems (where a program may not have complete control of a variable)
and multi-threaded applications. The syntax for volatile qualifier is
✞
✌
✆
auto Qualifier
auto is a modifier which specifies an “automatic” variable that is automatically created
when in scope and destroyed when out of scope. If you think this sounds like pretty much
what you’ve been doing all along when you declare a variable, you’re right: all declared
items within a block are implicitly “automatic”. For this reason, the auto keyword is
more like the answer to a trivia question than a useful modifier, and there are lots of very
competent programmers that are unaware of its existence.
56. 56 Basic C++
Property Default Value
Keyword used auto
Storage Memory
Default value Garbage value or random value
Scope Local to the block in which it is defined
Lifetime Value persists till the control remains within the block
Keyword optionality Optional
Table 1.4: Features of auto variable.
In following example, b has declared as automatic variable and it has scope only inside
the block where it is declare. Here, b is declared outside the main function block, so on
compilation, it shows an error.
✞
#include <iostream >
2 using namespace std;
4 /* Automatic variable b*/
auto int b = 10;
6
int main (int argc , char ** argv ) {
8 auto int a = 5;
a++;
10 cout << a << endl ;
cout << b << endl ;
12 return 0;
}
✌
✆
In following example, variable ‘b’ is global integer while a is defined as automatic inside
the main() function. Hence variable ‘a’ and ‘b’ are accessible inside the main() function.
✞
1 #include <iostream >
using namespace std;
3
/*b has declared as global.*/
5 int b = 10;
7 int main (int argc , char ** argv ) {
auto int a = 5;
9 a++;
cout << a << endl ;
11 cout << b << endl ;
return 0;
13 }
✌
✆
✞
a : 6
57. 1.3. VARIABLES 57
b : 10
✌
✆
When defining a variable, we dont actually need to state its type explicitly when it can
be deduced from the auto initializer. With auto, we use the = syntax because there is no
type conversion involved that might cause problems. See the example below:
✞
#include <iostream >
2 using namespace std;
4 int main (int argc , char *argv []) {
auto i = ’c’;
6 cout << i;
return 0;
8 }
✌
✆
✞
c
✌
✆
register Qualifier
register is a hint to the compiler to attempt to optimize the storage of the given variable by
storing it in a register of the computer’s CPU when the program is run. Most optimizing
compilers do this anyway, so use of this keyword is often unnecessary. In fact, ANSI C
states that a compiler can ignore this keyword if it so desires and many do. Microsoft
Visual C++ is an example of an implementation that completely ignores the register
keyword.
Property Default Value
Keyword used register
Storage CPU registers (values can be retrieved faster
than from memory)
Default value Garbage value
Scope Local to the block in which it is defined
Lifetime Value persists till the control remains within
the block
Keyword optionality Mandatory to use the keyword
Table 1.5: Features of register variable.
Example for register type variable is given below.
✞
1 #include <iostream >
using namespace std;
3
int main (int argc , char ** argv ) {
58. 58 Basic C++
5 register int i;
7 for (i = 0; i < 5; i++) {
cout << "Value is " << i << endl ;
9 }
return 0;
11 }
✌
✆
✞
Value is 0
Value is 1
Value is 2
Value is 3
Value is 4
✌
✆
1.4 C++ Operators
C++ operators follows the precedence mechanism. If an operator is above to the other
operator in precedence order then it is executed first. If more than one operators are
there in an expression, then parentheses bracket are used to group them.
1.4.1 Arithmetic Operators
Arithmetic operators are those one, which are used in mathematics operations, like addi-
tion, subtraction, multiplication, division, remainder and assignment. Arithmetic opera-
tion symbols and their applications are explained in the table given below:
59. 1.4. C++ OPERATORS 59
Operator Description
+ Addition operator. It adds right value
with left value.
− Subtraction operator. It subtracts right
value from left value.
/ Division operator. It divides left value
with right value. Returns the quotient.
If, both left and right values are inte-
ger then decimal part of the result is
truncated.
∗ Multiplication operator. It multiply
left value with right value. It returns
product of two numbers.
% Modulus operator. Returns remainder
part in division.
= Assignment operator. A variable in left
side to this operator is assigned a value
given at the right side of this operator.
Table 1.6: Arithmetic operators.
In mathematics, there may be a single arithmetic operator or multiple operators.
Multiple operators in a single computation is known as expression. In following example,
equation line y = 5 + 3 − 4 is an arithmetic expression.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char *argv []) {
int y;
7 /* In first step 5+3=8. In *
* second step 8-4 = 4. As *
9 * + has higher precedence */
y = 5 + 3 - 4;
11 cout << "Result is : " << y << endl ;
return 0;
13 }
✌
✆
✞
Result is : 4
✌
✆
Arithmetic operators can be used between different data-types in C++. In C++, ‘+’
operator has arithmetic as well string concatenation property. See the following example
in which two strings ‘s’ and ‘t’ are concatenated with operator ‘+’. The number of strings
to be concatenated may be two or more.
60. 60 Basic C++
✞
1 #include <string >
#include <iostream >
3 using namespace std;
5 int main (int argc , char *argv []) {
string s, t, line ;
7 s = "This is a tree .";
t = "This is a mango tree .";
9 line = s + " " + t;
cout << line ;
11 }
✌
✆
Here, ‘s’, ‘t’ and ‘line’ are three string variables. Strings, assigned to variables ‘s’ and
‘t’ are concatenated by using ‘+’ operator and string result is assigned to variable ‘line’.
The final result is put at output stream by using operator cout.
✞
This is a tree . This is a mango tree .
✌
✆
1.4.2 Expression
An expression is a combination of one or more explicit values, constants, variables, oper-
ators and functions. The evaluated value of expression is assigned to another variable or
printed in output stream. A function declared as void returns void value the this return
value is discarded in the expression. An algebraic function is given below:
y = x2
+ 3x − 2
1.4.3 Unary Operators
In unary operations, an operator has only one operand. The unary operators, which are
used in C++, are given in below table.
61. 1.4. C++ OPERATORS 61
Table 1.7: Unary operators.
Type Representation
Increment ++x, x++
Decrement – – x, x – –
Address &x
Indirection *x
Positive +x
Negative –x
Ones‘ complement ∼ x
Logical negation !x
Sizeof sizeof x, sizeof (type-name)
Cast (type-name) cast-expression
‘type-name’ is the data type like, int, char, float or double etc. ‘cast-expression’ is
variable which is being converted from one data type to other data type. In the following
example, ‘–’ operator is used as negate operator. It changes the sign of the number.
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char *argv []) {
7 cout << "Negative of 2 is " << -2 << endl ;
return 0;
9 }
✌
✆
✞
Negative of 2 is -2
✌
✆
1.4.4 Binary Relation Operators
Binary operators are those operators which require two operands. These operators are
addition, subtraction, multiplication, division, less than, greater than, equals to etc. The
relational binary operators are
62. 62 Basic C++
Operator Description
< Less than
> Greater than
≤ Less than or equal to
≥ Greater than or equal to
== Equals
! = Not equals
In relation, a < b indicates that ‘a’ is less than ‘b’ and ‘a’ may have infinite numbers
of values which are lesser than ‘b’, i.e. (−∞, b). The value of ‘a’ shall be positive or
negative depends on the value of ‘b’. a ≤ b is similar to a < b except ‘a’ can also be equal
to ‘b’, i.e. (−∞, b]. a == b indicates than ‘a’ is exactly equal to ‘b’ and ‘a’ have no other
value than ‘b’. a! = b means ‘a’ never be equal to ‘b’. ‘a’ may be lesser than or greater
than ‘b’, i.e. (−∞, ∞)-(b).
✞
1 #include <cstdlib >
#include <iostream >
3 using namespace std;
5 int main (int argc , char *argv []) {
int a = 5;
7 int b = 2;
int c = 5;
9 if (a < b) {
cout << a << " is less than " << b << endl ;
11 }
if (a > b) {
13 cout << a << " is greater than " << b << endl ;
}
15 if (a <= c) {
cout << a << " is either less than or equal to " << c <<
endl ;
17 }
if (a == c) {
19 cout << a << " is exactly equal to " << c << endl ;
}
21 if (a != b) {
cout << a << " is not equal to " << b << endl ;
23 }
return 0;
25 }
✌
✆
Output of above program is
✞
5 is greater than 2
5 is either less than or equal to 5
5 is exactly equal to 5