Basicsof C++
Basicsof C++
Basicsof C++
Type Keyword
Boolean bool
Character char
Integer int
signed
unsigned
short
long
The following table shows the variable type, how much memory it
takes to store the value in memory, and what is maximum and
minimum value which can be stored in such type of variables.
#include <iostream>
int main() {
cout << "Size of short int : " << sizeof(short int) << endl;
cout << "Size of long int : " << sizeof(long int) << endl;
return 0;
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
typedef Declarations
You can create a new name for an existing type using typedef.
Following is the simple syntax to define a new type using typedef
−
For example, the following tells the compiler that feet is another
name for int −
feet distance;
Enumerated Types
An enumerated type declares an optional type name and a set of
zero or more identifiers that can be used as values of the type.
Each enumerator is a constant whose type is the enumeration.
By default, the value of the first name is 0, the second name has
the value 1, and the third has the value 2, and so on. But you can
give a name, a specific value by adding an initializer. For
example, in the following enumeration, green will have the value
5.
Here, blue will have a value of 6 because each name will be one
greater than the one that precedes it.
1
bool
2
char
3
int
4
float
5
double
6
void
Represents the absence of type.
7
wchar_t
type variable_list;
Here, type must be a valid C++ data type including char, w_char,
int, float, double, bool or any user-defined object, etc.,
and variable_list may consist of one or more identifier names
separated by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and
k; which instructs the compiler to create variables named i, j and
k of type int.
Example
Try the following example where a variable has been declared at
the top, but it has been defined inside the main function −
Live Demo
#include <iostream>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main () {
// Variable definition:
int a, b;
int c;
float f;
// actual initialization
a = 10;
b = 20;
c = a + b;
f = 70.0/3.0;
return 0;
30
23.3333
Same concept applies on function declaration where you provide
a function name at the time of its declaration and its actual
definition can be given anywhere else. For example −
// function declaration
int func();
int main() {
// function call
int i = func();
}
// function definition
int func() {
return 0;
}
int g = 20;
Local Variables
Variables that are declared inside a function or block are local
variables. They can be used only by statements that are inside
that function or block of code. Local variables are not known to
functions outside their own. Following is the example using local
variables −
Live Demo
#include <iostream>
int main () {
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
Global Variables
Global variables are defined outside of all the functions, usually
on top of the program. The global variables will hold their value
throughout the life-time of your program.
#include <iostream>
int g;
int main () {
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
A program can have same name for local and global variables but
value of local variable inside a function will take preference. For
example −
Live Demo
#include <iostream>
int g = 20;
int main () {
int g = 10;
cout << g;
return 0;
int 0
char '\0'
float 0
double 0
pointer NULL
C++ Constants/Literals
Constants refer to fixed values that the program may not alter
and they are called literals.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal
constant. A prefix specifies the base or radix: 0x or 0X for
hexadecimal, 0 for octal, and nothing for decimal.
212 // Legal
215u // Legal
0xFeeL // Legal
078 // Illegal: 8 is not an octal digit
032UU // Illegal: cannot repeat a suffix
85 // decimal
0213 // octal
0x4b // hexadecimal
30 // int
30u // unsigned int
30l // long
30ul // unsigned long
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a
fractional part, and an exponent part. You can represent floating
point literals either in decimal form or exponential form.
Boolean Literals
There are two Boolean literals and they are part of standard C++
keywords −
You should not consider the value of true equal to 1 and value of
false equal to 0.
Character Literals
Character literals are enclosed in single quotes. If the literal
begins with L (uppercase only), it is a wide character literal (e.g.,
L'x') and should be stored in wchar_t type of variable .
Otherwise, it is a narrow character literal (e.g., 'x') and can be
stored in a simple variable of char type.
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
#include <iostream>
int main() {
cout << "Hello\tWorld\n\n";
return 0;
Hello World
String Literals
String literals are enclosed in double quotes. A string contains
characters that are similar to character literals: plain characters,
escape sequences, and universal characters.
You can break a long line into multiple lines using string literals
and separate them using whitespaces.
Here are some examples of string literals. All the three forms are
identical strings.
"hello, dear"
"hello, \
dear"
Defining Constants
There are two simple ways in C++ to define constants −
#include <iostream>
#define LENGTH 10
#define WIDTH 5
int main() {
int area;
return 0;
50
#include <iostream>
using namespace std;
int main() {
int area;
return 0;
50
signed
unsigned
long
short
unsigned x;
unsigned int y;
#include <iostream>
*/
int main() {
j = 50000;
i = j;
return 0;
-15536 50000
The above result is because the bit pattern that represents 50,000 as a
short unsigned integer is interpreted as -15,536 by a short.
1
const
2
volatile
The modifier volatile tells the compiler that a variable's value may be
changed in ways not explicitly specified by the program.
3
restrict
auto
register
static
extern
mutable
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class,
auto can only be used within functions, i.e., local variables.
{
register int miles;
}
The register should only be used for variables that require quick access
such as counters. It should also be noted that defining 'register' does not
mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register depending on hardware and
implementation restrictions.
The static modifier may also be applied to global variables. When this is
done, it causes that variable's scope to be restricted to the file in which it
is declared.
In C++, when static is used on a class data member, it causes only one
copy of that member to be shared by all objects of its class.
#include <iostream>
// Function declaration
void func(void);
while(count--) {
func();
return 0;
// Function definition
i++;
std::cout << " and count is " << count << std::endl;
When the above code is compiled and executed, it produces the following
result −
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
When you have multiple files and you define a global variable or function,
which will be used in other files also, then extern will be used in another
file to give reference of defined variable or function. Just for
understanding extern is used to declare a global variable or function in
another file.
The extern modifier is most commonly used when there are two or more
files sharing the same global variables or functions as explained below.
#include <iostream>
int count ;
main() {
count = 5;
write_extern();
void write_extern(void) {
std::cout << "Count is " << count << std::endl;
}
Here, extern keyword is being used to declare count in another file. Now
compile these two files as follows −
This will produce write executable program, try to execute write and
check the result as follows −
$./write
5
Operators in C++
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Show Examples
Relational Operators
There are following relational operators supported by C++ language
Show Examples
Logical Operators
There are following logical operators supported by C++ language.
Examples
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The
truth tables for &, |, and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the
following table. Assume variable A holds 60 and variable B holds 13, then
−
Show Examples
Assignment Operators
There are following assignment operators supported by C++ language −
Show Examples
Operator Description Example
Misc Operators
The following table lists some other operators that C++ supports.
1
sizeof
2
Condition ? X : Y
3
,
4
. (dot) and -> (arrow)
6
&
Pointer operator & returns the address of a variable. For example &a;
will give actual address of the variable.
7
*
Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom. Within an expression,
higher precedence operators will be evaluated first.
Examples
1 while loop
2 for loop
Execute a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the
loop body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’
loop.
1 break statement
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
3 goto statement
Transfers control to the labeled statement. Though it is not advised to use
goto statement in your program.
#include <iostream>
int main () {
for( ; ; ) {
return 0;
1 if statement
3 switch statement
4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’
statement(s).
You can use one ‘switch’ statement inside another ‘switch’ statement(s).
The ? : Operator
We have covered conditional operator “? :” in previous chapter which can
be used to replace if...else statements. It has the following general form
−
Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of
the colon.
C++ Functions
A function is a group of statements that together perform a task. Every
C++ program has at least one function, which is main(), and all the
most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up
your code among different functions is up to you, but logically the
division usually is such that each function performs a specific task.
The C++ standard library provides numerous built-in functions that your
program can call. For example, function strcat() to concatenate two
strings, function memcpy() to copy one memory location to another
location and many more functions.
Defining a Function
The general form of a C++ function definition is as follows −
Example
Following is the source code for a function called max(). This function
takes two parameters num1 and num2 and return the biggest of both −
return result;
}
Function Declarations
A function declaration tells the compiler about a function name and how
to call the function. The actual body of the function can be defined
separately.
Calling a Function
While creating a C++ function, you give a definition of what the function
has to do. To use a function, you will have to call or invoke that function.
#include <iostream>
// function declaration
int main () {
int a = 100;
int b = 200;
int ret;
return 0;
int result;
result = num1;
else
result = num2;
return result;
I kept max() function along with main() function and compiled the source
code. While running final executable, it would produce the following
result −
Function Arguments
If a function is to use arguments, it must declare variables that accept
the values of the arguments. These variables are called the formal
parametersof the function.
The formal parameters behave like other local variables inside the
function and are created upon entry into the function and destroyed upon
exit.
While calling a function, there are two ways that arguments can be
passed to a function −
1 Call by Value
This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.
2 Call by Pointer
This method copies the address of an argument into the formal parameter.
Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect
the argument.
3 Call by Reference
This is done by using the assignment operator and assigning values for
the arguments in the function definition. If a value for that parameter is
not passed when the function is called, the default given value is used,
but if a value is specified, this default value is ignored and the passed
value is used instead. Consider the following example −
#include <iostream>
int result;
result = a + b;
return (result);
int main () {
int a = 100;
int b = 200;
int result;
result = sum(a);
return 0;
When the above code is compiled and executed, it produces the following
result −
Numbers in C++
Normally, when we work with Numbers, we use primitive data types such
as int, short, long, float and double, etc. The number data types, their
possible values and number ranges have been explained while discussing
C++ Data Types.
Live Demo
#include <iostream>
int main () {
// number definition:
short s;
int i;
long l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
return 0;
When the above code is compiled and executed, it produces the following
result −
short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4
1
double cos(double);
This function takes an angle (as a double) and returns the cosine.
2
double sin(double);
This function takes an angle (as a double) and returns the sine.
3
double tan(double);
This function takes an angle (as a double) and returns the tangent.
4
double log(double);
This function takes a number and returns the natural log of that number.
5
double pow(double, double);
The first is a number you wish to raise and the second is the power you
wish to raise it t
6
double hypot(double, double);
If you pass this function the length of two sides of a right triangle, it will
return you the length of the hypotenuse.
7
double sqrt(double);
You pass this function a number and it gives you the square root.
8
int abs(int);
This function returns the absolute value of an integer that is passed to it.
9
double fabs(double);
This function returns the absolute value of any decimal number passed to
it.
10
double floor(double);
Finds the integer which is less than or equal to the argument passed to it.
#include <iostream>
#include <cmath>
int main () {
// number definition:
short s = 10;
int i = -1000;
long l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
return 0;
When the above code is compiled and executed, it produces the following
result −
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
#include <iostream>
#include <ctime>
#include <cstdlib>
int main () {
int i,j;
j = rand();
return 0;
When the above code is compiled and executed, it produces the following
result −
Random Number : 1748144778
Random Number : 630873888
Random Number : 2134540646
Random Number : 219404170
Random Number : 902129458
Random Number : 920445370
Random Number : 1319072661
Random Number : 257938873
Random Number : 1256201101
Random Number : 580322989
C++ Arrays
Declaring Arrays
To declare an array in C++, the programmer specifies the type of the
elements and the number of elements required by an array as follows −
Initializing Arrays
You can initialize C++ array elements either one by one or using a single
statement as follows −
The number of values between braces { } can not be larger than the
number of elements that we declare for the array between square
brackets [ ]. Following is an example to assign a single element of the
array −
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write −
You will create exactly the same array as you did in the previous
example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of
50.0. Array with 4th index will be 5th, i.e., last element because all arrays
have 0 as the index of their first element which is also called base index.
Following is the pictorial representaion of the same array we discussed
above −
The above statement will take 10th element from the array and assign
the value to salary variable. Following is an example, which will use all
the above-mentioned three concepts viz. declaration, assignment and
accessing arrays −
#include <iostream>
#include <iomanip>
using std::setw;
int main () {
return 0;
}
This program makes use of setw() function to format the output. When
the above code is compiled and executed, it produces the following result
−
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Arrays in C++
Arrays are important to C++ and should need lots of more detail. There
are following few important concepts, which should be clear to a C++
programmer −
1 Multi-dimensional arrays
2 Pointer to an array
You can pass to the function a pointer to an array by specifying the array's
name without an index.
C++ Strings
If you follow the rule of array initialization, then you can write the above
statement as follows −
#include <iostream>
int main () {
return 0;
When the above code is compiled and executed, it produces the following
result −
1
strcpy(s1, s2);
2
strcat(s1, s2);
3
strlen(s1);
4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
5
strchr(s1, ch);
6
strstr(s1, s2);
#include <iostream>
#include <cstring>
char str3[10];
int len ;
cout << "strcpy( str3, str1) : " << str3 << endl;
cout << "strcat( str1, str2): " << str1 << endl;
len = strlen(str1);
return 0;
#include <iostream>
#include <string>
int main () {
string str3;
int len ;
str3 = str1;
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
C++ Pointers
C++ pointers are easy and fun to learn. Some C++ tasks are performed
more easily with pointers, and other C++ tasks, such as dynamic
memory allocation, cannot be performed without them.
#include <iostream>
int main () {
int var1;
char var2[10];
return 0;
When the above code is compiled and executed, it produces the following
result −
type *var-name;
Here, type is the pointer's base type; it must be a valid C++ type
and var-name is the name of the pointer variable. The asterisk you used
to declare a pointer is the same asterisk that you use for multiplication.
However, in this statement the asterisk is being used to designate a
variable as a pointer. Following are the valid pointer declaration −
The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that the
pointer points to.
#include <iostream>
int main () {
Pointers in C++
Pointers have many but easy concepts and they are very important to
C++ programming. There are following few important pointer concepts
which should be clear to a C++ programmer −
1 Null Pointers
C++ supports null pointer, which is a constant with a value of zero defined
in several standard libraries.
2 Pointer Arithmetic
There are four arithmetic operators that can be used on pointers: ++, --,
+, -
3 Pointers vs Arrays
4 Array of Pointers
5 Pointer to Pointer
C++ References
References vs Pointers
References are often confused with pointers but three major differences
between references and pointers are −
int i = 17;
int& r = i;
Read the & in these declarations as reference. Thus, read the first
declaration as "r is an integer reference initialized to i" and read the
second declaration as "s is a double reference initialized to d.". Following
example makes use of references on int and double −
#include <iostream>
int main () {
int i;
double d;
int& r = i;
double& s = d;
i = 5;
cout << "Value of i : " << i << endl;
d = 11.7;
return 0;
When the above code is compiled together and executed, it produces the
following result −
Value of i : 5
Value of i reference : 5
Value of d : 11.7
Value of d reference : 11.7
References are usually used for function argument lists and function
return values. So following are two important subjects related to C++
references which should be clear to a C++ programmer −
1 References as Parameters
You can return reference from a C++ function like any other data type.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow
from a device like a keyboard, a disk drive, or a network connection etc.
to main memory, this is called input operation and if bytes flow from
main memory to a device like a display screen, a printer, a disk drive, or
a network connection, etc., this is called output operation.
1
<iostream>
This file defines the cin, cout, cerr and clog objects, which correspond to
the standard input stream, the standard output stream, the un-buffered
standard error stream and the buffered standard error stream,
respectively.
2
<iomanip>
This file declares services useful for performing formatted I/O with so-
called parameterized stream manipulators, such
as setw and setprecision.
3
<fstream>
#include <iostream>
int main() {
When the above code is compiled and executed, it produces the following
result −
The C++ compiler also determines the data type of variable to be output
and selects the appropriate stream insertion operator to display the
value. The << operator is overloaded to output data items of built-in
types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single
statement as shown above and endl is used to add a new-line at the end
of the line.
#include <iostream>
int main() {
char name[50];
cout << "Your name is: " << name << endl;
When the above code is compiled and executed, it will prompt you to
enter a name. You enter a value and then hit enter to see the following
result −
The C++ compiler also determines the data type of the entered value
and selects the appropriate stream extraction operator to extract the
value and store it in the given variables.
The stream extraction operator >> may be used more than once in a
single statement. To request more than one datum you can use the
following −
The cerr is also used in conjunction with the stream insertion operator as
shown in the following example.
#include <iostream>
int main() {
When the above code is compiled and executed, it produces the following
result −
The clog is also used in conjunction with the stream insertion operator
as shown in the following example.
#include <iostream>
int main() {
When the above code is compiled and executed, it produces the following
result −
You would not be able to see any difference in cout, cerr and clog with
these small examples, but while writing and executing big programs the
difference becomes obvious. So it is good practice to display error
messages using cerr stream and while displaying other log messages
then clog should be used.