C++

C++ Tutorial
C++ is a middle-level programming language developed by Bjarne Stroustrup starting in 1979 at Bell Labs. C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
This reference will take you through simple and practical approach while learning C++ Programming language.
C++ is a statically typed, compiled, general purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming.
C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features.
C++ was developed by Bjarne Stroustrup starting in 1979 at Bell Labs in Murray Hill, New Jersey as an enhancement to the C language and originally named C with Classes but later it was renamed C++ in 1983.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.

C++ Compiler:

This is actual C++ compiler which will be used to compile your source code into final executable program.
Most C++ compilers don't care what extension you give your source code, but if you don't specify otherwise, many will use .cpp by default
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have respective Operating Systems.

C++ Program Structure:

Let us look at a simple code that would print the words Hello World.
#include <iostream>
using namespace std;
 
// main() is where program execution begins.
 
int main()
{
   cout << "Hello World"; // prints Hello World
   return 0;
}

Comments in C++

C++ supports single line and multi-line comments. All characters available inside any comment are ignored by C++ compiler.
C++ comments start with /* and end with */. For example:
/* This is a comment */
 
/* C++ comments can  also
 * span multiple lines
 */
A comment can also start with //, extending to the end of the line. For example:
#include <iostream>
using namespace std;
 
main()
{
   cout << "Hello World"; // prints Hello World
 
   return 0;
}

C++ Primitive Built-in Types:

C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table list down seven basic C++ data types:
TypeKeyword
Booleanbool
Characterchar
Integerint
Floating pointfloat
Double floating pointdouble
Valuelessvoid
Wide characterwchar_t

Variable Declaration & Initialization in C++:

Some examples are:
int d = 3, f = 5;    // initializing d and f.
byte z = 22;         // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x';        // the variable x has the value 'x'.

----------------------------------------------------------------------------------------------------------------------------

C++ Variable Scope:

A scope is a region of the program and broadly speaking there are three places where variables can be declared:
  • Inside a function or a block which is called local variables,
  • In the definition of function parameters which is called formal parameters.
  • Outside of all functions which is called global variables.

C++ Constants/Literals:

Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided in Integer Numerals, Floating-Point Numerals, Characters, Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values cannot be modified after their definition.

C++ Modifier Types:

C++ allows the char, int, and double data types to have modifiers preceding them. A modifier is used to alter the meaning of the base type so that it more precisely fits the needs of various situations.
The data type modifiers are listed here:
  • signed
  • unsigned
  • long
  • short
The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition,signed and unsigned can be applied to char, and long can be applied to double.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For exampleunsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without the int. The int is implied. For example, the following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;

Storage Classes in C++:

A storage class defines the scope (visibility) and life time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes which can be used in a C++ Program
  • auto
  • register
  • static
  • extern
  • mutable

C++ Operators:

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides following type of operators:
  • Arithmetic Operators ( +, -, \, *, ++, --)
  • Relational Operators (==, !=, >. <, >=, <=)
  • Logical Operators (&&, ||, ! )
  • Bitwise Operators (& |, ^, ~, <<, >>)
  • Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=)
  • Misc Operators ( sizeof, & cast, comma, conditional etc.)

C++ Loop Types:

C++ programming language provides following types of loop to handle looping requirements. Click the following links to check their detail.
Loop TypeDescription
while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
do...while loopLike a while statement, except that it tests the condition at the end of the loop body
nested loopsYou can use one or more loop inside any another while, for or do..while loop.

C++ Decision Making:

C++ programming language provides following types of decision making statements. Click the following links to check their detail.
StatementDescription
if statementAn if statement consists of a boolean expression followed by one or more statements.
if...else statementAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.
switch statementA switch statement allows a variable to be tested for equality against a list of values.
nested if statementsYou can use one if or else if statement inside another if or else if statement(s).
nested switch statementsYou can use one swicth statement inside another switch statement(s).

C++ Functions:

The general form of a C++ function definition is as follows:
return_type function_name( parameter list )
{
   body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts of a function:
  • Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
  • Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
  • Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
  • Function Body: The function body contains a collection of statements that define what the function does.

Numbers in C++:

Following a simple example to show few of the mathematical operations on C++ numbers:
#include <iostream>
#include <cmath>
using namespace std;
 
int main ()
{
   // number definition:
   short  s = 10;
   int    i = -1000;
   long   l = 100000;
   float  f = 230.47;
   double d = 200.374;
 
   // mathematical operations;
   cout << "sin(d) :" << sin(d) << endl;
   cout << "abs(i)  :" << abs(i) << endl;
   cout << "floor(d) :" << floor(d) << endl;
   cout << "sqrt(f) :" << sqrt(f) << endl;
   cout << "pow( d, 2) :" << pow(d, 2) << endl;
 
   return 0;
}

----------------------------------------------------------------------------------------------------------------------------

C++ Arrays:

Following is an example which will show array declaration, assignment and accessing arrays in C++:
#include <iostream>
using namespace std;
 
#include <iomanip>
using std::setw;
 
int main ()
{
   int n[ 10 ]; // n is an array of 10 integers
 
   // initialize elements of array n to 0          
   for ( int i = 0; i < 10; i++ )
   {
      n[ i ] = i + 100; // set element at location i to i + 100
   }
   cout << "Element" << setw( 13 ) << "Value" << endl;
 
   // output each array element's value                      
   for ( int j = 0; j < 10; j++ )
   {
      cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
   }
 
   return 0;
}

----------------------------------------------------------------------------------------------------------------------------

C++ Strings:

C++ provides following two types of string representations:
The C-style character string as follows:
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. Following is the example:
#include <iostream>
#include <string>
 
using namespace std;
 
int main ()
{
   string str1 = "Hello";
   string str2 = "World";
   string str3;
 
   // copy str1 into str3
   str3 = str1;
   cout << "str3 : " << str3 << endl;
 
   // concatenates str1 and str2
   str3 = str1 + str2;
   cout << "str1 + str2 : " << str3 << endl;
  
   return 0;
}

C++ Classes & Objects

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations. For example we defined the Box data type using the keyword class as follows:
class Box
{
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};
The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. You can also specify the members of a class as private or protected which we will discuss in a sub-section.

Define C++ Objects:

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:
Box Box1;          // Declare Box1 of type Box
Box Box2;          // Declare Box2 of type Box
Both of the objects Box1 and Box2 will have their own copy of data members.

Accessing the Data Members:

The public data members of objects of a class can be accessed using the direct member access operator (.). Let us try following example to make the things clear:
#include <iostream>
 
using namespace std;
 
class Box
{
   public:
      double length;   // Length of a box
      double breadth;  // Breadth of a box
      double height;   // Height of a box
};
 
int main( )
{
   Box Box1;        // Declare Box1 of type Box
   Box Box2;        // Declare Box2 of type Box
   double volume = 0.0;     // Store the volume of a box here
 
   // box 1 specification
   Box1.height = 5.0; 
   Box1.length = 6.0; 
   Box1.breadth = 7.0;
 
   // box 2 specification
   Box2.height = 10.0;
   Box2.length = 12.0;
   Box2.breadth = 13.0;
   // volume of box 1
   volume = Box1.height * Box1.length * Box1.breadth;
   cout << "Volume of Box1 : " << volume <<endl;
 
   // volume of box 2
   volume = Box2.height * Box2.length * Box2.breadth;
   cout << "Volume of Box2 : " << volume <<endl;
   return 0;
}

----------------------------------------------------------------------------------------------------------------------------

C++ Inheritance:

One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class. This existing class is called the base class, and the new class is referred to as the derived class.
A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form:
class derived-class: access-specifier base-class
Where access-specifier is one of public, protected, or private, and base-class is the name of a previously defined class. If the access-specifier is not used, then it is private by default.
Consider a base class Shape and its derived class Rectangle as follows:
#include <iostream>
 
using namespace std;
 
// Base class
class Shape 
{
   public:
      void setWidth(int w)
      {
         width = w;
      }
      void setHeight(int h)
      {
         height = h;
      }
   protected:
      int width;
      int height;
};
 
// Derived class
class Rectangle: public Shape
{
   public:
      int getArea()
      { 
         return (width * height); 
      }
};
 
int main(void)
{
   Rectangle Rect;
 
   Rect.setWidth(5);
   Rect.setHeight(7);
 
   // Print the area of the object.
   cout << "Total area: " << Rect.getArea() << endl;
 
   return 0;
}

----------------------------------------------------------------------------------------------------------------------------

C++ Overloading

C++ allows you to specify more than one definition for a function name or an operator in the same scope, which is called function overloading and operator overloading respectively.
Following is the example where same function print() is being used to print different data types:
#include <iostream>
using namespace std;
 
class printData 
{
   public:
      void print(int i) {
        cout << "Printing int: " << i << endl;
      }
 
      void print(double  f) {
        cout << "Printing float: " << f << endl;
      }
 
      void print(char* c) {
        cout << "Printing character: " << c << endl;
      }
};
 
int main(void)
{
   printData pd;
 
   // Call print to print integer
   pd.print(5);
   // Call print to print float
   pd.print(500.263);
   // Call print to print character
   pd.print("Hello C++");
 Ignore warning
   return 0;
}

----------------------------------------------------------------------------------------------------------------------------

Polymorphism in C++

C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two classes and area() method has been implemented by the two sub-classes with different implementation.
#include <iostream> 
using namespace std;
 
class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0)
      {
        Shape(a, b); 
      }
      int area ()
      { 
         cout << "Rectangle class area :" <<endl;
         return (width * height); 
      }
};
class Triangle: public Shape{
   public:
      Triangle( int a=0, int b=0)
      {
        Shape(a, b); 
      }
      int area ()
      { 
         cout << "Rectangle class area :" <<endl;
         return (width * height / 2); 
      }
};
// Main function for the program
int main( )
{
   Shape *shape;
   Rectangle rec(10,7);
   Triangle  tri(10,5);
 
   // store the address of Rectangle
   shape = &rec;
   // call rectangle area.
   shape->area();
 
   // store the address of Triangle
   shape = &tri;
   // call triangle area.
   shape->area();
   
   return 0;
}

Data Abstraction in C++:

Data abstraction refers to, providing only essential information to the outside word and hiding their background details ie. to represent the needed information in program without presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation.
For example, in C++ we use classes to define our own abstract data types (ADT). You can use the coutobject of class ostream to stream data to standard output like this:
#include <iostream>
using namespace std;
 
int main( )
{
   cout << "Hello C++" <<endl;
   return 0;
}
Here you don't need to understand how cout displays the text on the user's screen. You need only know the public interface and the underlying implementation of cout is free to change.

Data Encapsulation in C++:

All C++ programs are composed of following two fundamental elements:
  • Program statements (code): This is the part of a program that performs actions and they are called functions.
  • Program data: The data is the information of the program which affected by the program functions.
Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding.
C++ supports the properties of encapsulation and data hiding through the creation of user-defined types, called classes. We already have studied that a class can contain private, protected and publicmembers. By default, all items defined in a class are private. For example:
class Box
{
   public:
      double getVolume(void)
      {
         return length * breadth * height;
      }
   private:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
};

C++ Files and Streams:

The iostream standard library cin and cout methods for reading from standard input and writing to standard output respectively.
To read and write from a file requires another standard C++ library called fstream which defines three new data types:
Data TypeDescription
ofstreamThis data type represents the output file stream and is used to create files and to write information to files.
ifstreamThis data type represents the input file stream and is used to read information from files.
fstreamThis data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
Following is the C++ program which opens a file in reading and writing mode. After writing information inputted by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;
 
int main ()
{
    
   char data[100];
 
   // open a file in write mode.
   ofstream outfile;
   outfile.open("afile.dat");
 
   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);
 
   // write inputted data into the file.
   outfile << data << endl;
 
   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // again write inputted data into the file.
   outfile << data << endl;
 
   // close the opened file.
   outfile.close();
 
   // open a file in read mode.
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 
 
   // write the data at the screen.
   cout << data << endl;
   
   // again read the data from the file and display it.
   infile >> data; 
   cout << data << endl; 
 
   // close the opened file.
   infile.close();
 
   return 0;
}

Hope you already understand the concept of C++ Template which we already have discussed in one of the chapters. The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provides general-purpose templatized classes and functions that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.

At the core of the C++ Standard Template Library are following three well-structured components:
ComponentDescription
ContainersContainers are used to manage collections of objects of a certain kind. There are several different types of containers like deque, list, vector, map etc.
AlgorithmsAlgorithms act on containers. They provide the means by which you will perform initialization, sorting, searching, and transforming of the contents of containers.
IteratorsIterators are used to step through the elements of collections of objects. These collections may be containers or subsets of containers.

We will discuss about all the three C++ STL components in next chapter while discussing C++ Standard Library. For now, keep in mind that all the three components have a rich set of pre-defined functions which help us in doing complicated tasks in very easy fashion.

Let us take the following program demonstrates the vector container (a C++ Standard Template) which is similar to an array with an exception that it automatically handles its own storage requirements in case it grows:

#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
   // create a vector to store int
   vector<int> vec; 
   int i;

   // display the original size of vec
   cout << "vector size = " << vec.size() << endl;

   // push 5 values into the vector
   for(i = 0; i < 5; i++){
      vec.push_back(i);
   }

   // display extended size of vec
   cout << "extended vector size = " << vec.size() << endl;

   // access 5 values from the vector
   for(i = 0; i < 5; i++){
      cout << "value of vec [" << i << "] = " << vec[i] << endl;
   }

   // use iterator to access the values
   vector<int>::iterator v = vec.begin();
   while( v != vec.end()) {
      cout << "value of v = " << *v << endl;
      v++;
   }

   return 0;
}

When the above code is compiled and executed, it produces following result:
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4
Here are following points to be noted related to various functions we used in the above example:

  • The push_back( ) member function inserts value at the end of the vector, expanding its size as needed.
  • The size( ) function displays the size of the vector.
  • The function begin( ) returns an iterator to the start of the vector.
  • The function end( ) returns an iterator to the end of the vector.


    When we consider a C++ program it can be defined as a collection of objects that communicate via invoking each others methods. Let us now briefly look into what do class, object, methods and instant variables mean.
    • Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
    • Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.
    • Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
    • Instant Variables - Each object has its unique set of instant variables. An object's state is created by the values assigned to these instant variables.

    C++ Program Structure:

    Let us look at a simple code that would print the words Hello World.
    #include <iostream>
    using namespace std;
    
    // main() is where program execution begins.
    
    int main()
    {
       cout << "Hello World"; // prints Hello World
       return 0;
    }
    Let us look various parts of the above program:
    • The C++ language defines several headers, which contain information that is either necessary or useful to your program. For this program, the header <iostream> is needed.
    • The line using namespace std; tells the compiler to use the std namespace. Namespaces are a relatively recent addition to C++.
    • The next line // main() is where program execution begins. is a single-line comment available in C++. Single-line comments begin with // and stop at the end of the line.
    • The line int main() is the main function where program execution begins.
    • The next line cout << "This is my first C++ program."; causes the message "This is my first C++ program" to be displayed on the screen.
    • The next line return 0; terminates main( )function and causes it to return the value 0 to the calling process.

    Compile & Execute C++ Program:

    Lets look at how to save the file, compile and run the program. Please follow the steps given below:
    • Open a text editor and add the code as above.
    • Save the file as : hello.cpp
    • Open a command prompt and go to the directory where you saved the file.
    • Type 'g++ hello.cpp ' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line and would generate a.out executable file.
    • Now type ' a.out' to run your program.
    • You will be able to see ' Hello World ' printed on the window.
    $ g++ hello.cpp
    $ ./a.out
    Hello World
    Make sure that g++ is in your path and that you are running it in the directory containing file hello.cpp.
    You can compile C/C++ programs using makefile. For more detail you can check Makefile Tutorial.

    Semicolons & Blocks in C++:

    In C++, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.
    For example, following are three different statements:
    x = y;
    y = y+1;
    add(x, y);
    A block is a set of logically connected statements that are surrounded by opening and closing braces. For example:
    {
       cout << "Hello World"; // prints Hello World
       return 0;
    }
    C++ does not recognize the end of the line as a terminator. For this reason, it does not matter where on a line you put a statement. For example:
    x = y;
    y = y+1;
    add(x, y);
    is the same as
    x = y; y = y+1; add(x, y);

    C++ Identifiers:

    A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
    C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a case sensitive programming language. Thus Manpower and manpower are two different identifiers in C++.
    Here are some examples of acceptable identifiers:
    mohd       zara    abc   move_name  a_123
    myname50   _temp   j     a23b9      retVal

    C++ Keywords:

    The following list shows the reserved words in C++. These reserved words may not be used as constant or variable or any other identifier names.
    asmelsenewthis
    autoenumoperatorthrow
    boolexplicitprivatetrue
    breakexportprotectedtry
    caseexternpublictypedef
    catchfalseregistertypeid
    charfloatreinterpret_casttypename
    classforreturnunion
    constfriendshortunsigned
    const_castgotosignedusing
    continueifsizeofvirtual
    defaultinlinestaticvoid
    deleteintstatic_castvolatile
    dolongstructwchar_t
    doublemutableswitchwhile
    dynamic_castnamespacetemplate

    Trigraphs:

    A few characters have an alternative representation, called a trigraph sequence. A trigraph is a three-character sequence that represents a single character and the sequence always starts with two question marks.
    Trigraphs are expanded anywhere they appear, including within string literals and character literals, in comments, and in preprocessor directives.
    Following are most frequently used trigraph sequences:
    TrigraphReplacement
    ??=#
    ??/\
    ??'^
    ??([
    ??)]
    ??!|
    ??<{
    ??>}
    ??-~
    All the compilers do not support trigraphs and they are not advised to be used because of their confusing nature.

    Whitespace in C++:

    A line containing only whitespace, possibly with a comment, is known as a blank line, and C++ compiler totally ignores it.
    Whitespace is the term used in C++ to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the statement,
    int age;
    There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the statement
    fruit = apples + oranges;   // Get the total fruit
    No whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.

    C++ Data Types

    While doing programming in any programming language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

    You may like to store information of various data type like character, wide character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.

    Primitive Built-in Types:

    C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table list down seven basic C++ data types:
    TypeKeyword
    Booleanbool
    Characterchar
    Integerint
    Floating pointfloat
    Double floating pointdouble
    Valuelessvoid
    Wide characterwchar_t
    Several of the basic types can be modified using one or more of these type modifiers:
    • signed
    • unsigned
    • short
    • long
    The following table shows the variable type, how much memory it takes to store the value memory, and what is maximum and minimum vaue which can be stored in such type of variables.
    TypeTypical Bit WidthTypical Range
    char1byte-127 to 127 or 0 to 255
    unsigned char1byte0 to 255
    signed char1byte-127 to 127
    int4bytes-2147483648 to 2147483647
    unsigned int4bytes0 to 4294967295
    signed int4bytes-2147483648 to 2147483647
    short int2bytes-32768 to 32767
    unsigned short intRange0 to 65,535
    signed short intRange-32768 to 32767
    long int4bytes-2,147,483,647 to 2,147,483,647
    signed long int4bytessame as long int
    unsigned long int4bytes0 to 4,294,967,295
    float4bytes+/- 3.4e +/- 38 (~7 digits)
    double8bytes+/- 1.7e +/- 308 (~15 digits)
    long double8bytes+/- 1.7e +/- 308 (~15 digits)
    wchar_t2 or 4 bytes1 wide character
    The sizes of variables might be different from those shown in the above table, depending on the compiler and the computer you are using.
    Following is the example which will produce correct size of various data type on your cmputer.
    #include <iostream>
    using namespace std;
    
    int main()
    {
       cout << "Size of char : " << sizeof(char) << endl;
       cout << "Size of int : " << sizeof(int) << endl;
       cout << "Size of short int : " << sizeof(short int) << endl;
       cout << "Size of long int : " << sizeof(long int) << endl;
       cout << "Size of float : " << sizeof(float) << endl;
       cout << "Size of double : " << sizeof(double) << endl;
       cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
       return 0;
    }
    This example uses endl which inserts a new-line character after every line and << operator is being used to pass multiple values out to the screen. We are also using sizeof() function to get size of various data types.
    When the above code is compiled and executed, it produces following result which can vary from machine to machine:
    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:
    typedef type newname; 
    For example, the following tells the compiler that feet is another name for int:
    typedef int feet;
    Now, the following declaration is perfectly legal and creates an integer variable called distance:
    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.
    To create an enumeration requires the use of the keyword enum. The general form of an enumeration type is:
    enum enum-name { list of names } var-list; 
    Here, The enum-name is the enumeration's type name. The list of names is comma separated.
    For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value "blue".
    enum color { red, green, blue } c;
    c = blue;
    By default, the value of the first name is 0, the second name has the value 1, 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.
    enum color { red, green=5, blue };
    Here blue will have a value of 6 because each name will be one greater than the one that precedes it.



    C++ Variable Types

    A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
    The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++ is case-sensitive:
    There are following basic types of variable in C++ as explained in last chapter:
    TypeDescription
    boolStores either value true or false.
    charTypically a single octet(one byte). This is an integer type.
    intThe most natural size of integer for the machine.
    floatA single-precision floating point value.
    doubleA double-precision floating point value.
    voidRepresents the absence of type.
    wchar_tA wide character type.
    C++ also allows to define various other type of variables which we will cover in subsequent chapters like Enumeration, Pointer, Array, Reference, Data structures, and Classes.
    Following section will cover how to define, declare and use various type of variables.

    Variable Declaration in C++:

    All variables must be declared before use, although certain declarations can be made implicitly by content. A declaration specifies a type, and contains a list of one or more variables of that type as follows:
    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;
    A variable declaration with an initializer is always a definition. This means that storage is allocated for the variable and could be declared as follows:
    int    i = 100;
    An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be declared multiple times in a program, but it must be defined only once. Following is the declaration of a variable with extern keyword:
    extern int    i;
    Though you can declare a variable multiple times in your C++ program but it can be decalred only once in a file, a function or a block of code.

    Variable Initialization in C++:

    Variables are initialized (assigned an value) with an equal sign followed by a constant expression. The general form of initialization is:
    variable_name = value;
    Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:
    type variable_name = value;
    Some examples are:
    int d = 3, f = 5;    // initializing d and f.
    byte z = 22;         // initializes z.
    double pi = 3.14159; // declares an approximation of pi.
    char x = 'x';        // the variable x has the value 'x'.
    For declarations without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.
    It is a good programming practice to initialize variables properly otherwise, sometime program would produce unexpected result. Try following example which makes use of various types of variables:
    #include <iostream>
    using namespace std;
     
    int main ()
    {
      // Variable declaration:
      int a, b;
      int c;
      float f;
     
      // actual initialization
      a = 10;
      b = 20;
      c = a + b;
     
      cout << c << endl ;
    
      f = 70.0/3.0;
      cout << f << endl ;
     
      return 0;
    }
    When the above code is compiled and executed, it produces following result:
    30
    23.3333

    Lvalues and Rvalues:

    There are two kinds of expressions in C++:
    • lvalue : An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
    • rvalue : An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
    Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:
    int g = 20;
    But following is not a valid statement and would generate compile-time error:
    10 = 20;



    C++ Variable Scope 


    A scope is a region of the program and broadly speaking there are three places where variables can be declared:
    • Inside a function or a block which is called local variables,
    • In the definition of function parameters which is called formal parameters.
    • Outside of all functions which is called global variables.
    We will learn what is a function and it's parameter in subsequent chapters. Here let us explain what are local and global variables.

    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:
    #include <iostream>
    using namespace std;
     
    int main ()
    {
      // Local variable declaration:
      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 lifetime of your program.
    A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:
    #include <iostream>
    using namespace std;
     
    // Global variable declaration:
    int g;
     
    int main ()
    {
      // Local variable declaration:
      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:
    #include <iostream>
    using namespace std;
     
    // Global variable declaration:
    int g = 20;
     
    int main ()
    {
      // Local variable declaration:
      int g = 10;
     
      cout << g;
     
      return 0;
    }
    When the above code is compiled and executed, it produces following result:
    10

    Initializing Local and Global Variables:

    When a local variable is defined, it is not initalised by the system, you must initalise it yourself. Global variables are initalised automatically by the system when you define them as follows:
    Data TypeInitialser
    int0
    char'\0'
    float0
    double0
    pointerNULL
    It is a good programming practice to initialize variables properly otherwise, sometime program would produce unexpected result.

    Storage Classes in C++ 

    A storage class defines the scope (visibility) and life time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes which can be used in a C++ Program
    • auto
    • register
    • static
    • extern
    • mutable

    The auto Storage Class

    The auto storage class is the default storage class for all local variables.
    {
       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.

    The register Storage Class

    The register storage class is used to define local variables that should be stored in a register instead of RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have the unary '&' operator applied to it (as it does not have a memory location).
    {
       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' goes 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 Storage Class

    The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
    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);
     
    static int count = 10; /* Global variable */
     
    main()
    {
        while(count--)
        {
           func();
        }
        return 0;
    }
    // Function definition
    void func( void )
    {
        static int i = 5; // local static variable
        i++;
        std::cout << "i is " << i ;
        std::cout << " and count is " << count << std::endl;
    }
    When the above code is compiled and executed, it produces 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

    The extern Storage Class

    The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use 'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that has been previously defined.
    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 files.
    The extern modifier is most commonly used when there are two or more files sharing the same global variables or functions as explained below.
    First File: main.cpp
    #include <iostream>
     
    int count ;
    extern void write_extern();
     
    main()
    {
       count = 5;
       write_extern();
    }
    Second File: write.cpp
    #include <iostream>
     
    extern int count;
     
    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:
    $g++ main.cpp write.cpp -o write
    This will produce write executable program, try to execute write and check the result as follows:
    $./write
    5

    The mutable Storage Class

    The mutable specifier applies only to class objects, which are discussed later in this tutorial. It allows a member of an object to override constness. That is, a mutable member can be modified by a const member function.
    ----------------------------------------------------------------------------------------------------------------------------

    Operators in C++ 

    An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides following type of operators:
    • Arithmetic Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Assignment Operators
    • Misc Operators
    This chapter will examine the arithmetic, relational, and logical, bitwise, assignment and other operators one by one.

    Arithmetic Operators:

    There are following arithmetic operators supported by C++ language:
    Assume variable A holds 10 and variable B holds 20 then:
    Show Examples
    OperatorDescriptionExample
    +Adds two operandsA + B will give 30
    -Subtracts second operand from the firstA - B will give -10
    *Multiply both operandsA * B will give 200
    /Divide numerator by de-numeratorB / A will give 2
    %Modulus Operator and remainder of after an integer divisionB % A will give 0
    ++Increment operator, increases integer value by oneA++ will give 11
    --Decrement operator, decreases integer value by oneA-- will give 9

    Relational Operators:

    There are following relational operators supported by C++ language
    Assume variable A holds 10 and variable B holds 20 then:
    Show Examples
    OperatorDescriptionExample
    ==Checks if the value of two operands is equal or not, if yes then condition becomes true.(A == B) is not true.
    !=Checks if the value of two operands is equal or not, if values are not equal then condition becomes true.(A != B) is true.
    >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
    <Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
    >=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
    <=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

    Logical Operators:

    There are following logical operators supported by C++ language
    Assume variable A holds 1 and variable B holds 0 then:
    Show Examples
    OperatorDescriptionExample
    &&Called Logical AND operator. If both the operands are non zero then condition becomes true.(A && B) is false.
    ||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.(A || B) is true.
    !Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.

    Bitwise Operators:

    Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^ are as follows:
    pqp & qp | qp ^ q
    00000
    01011
    11110
    10011
    Assume if A = 60; and B = 13; Now in binary format they will be as follows:
    A = 0011 1100
    B = 0000 1101
    -----------------
    A&B = 0000 1100
    A|B = 0011 1101
    A^B = 0011 0001
    ~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
    OperatorDescriptionExample
    &Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
    |Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
    ^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
    ~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -60 which is 1100 0011
    <<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
    >>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

    Assignment Operators:

    There are following assignment operators supported by C++ language:
    Show Examples
    OperatorDescriptionExample
    =Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
    +=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
    -=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
    *=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
    /=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
    %=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
    <<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
    >>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
    &=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
    ^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
    |=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

    Misc Operators

    There are few other operators supported by C++ Language.
    OperatorDescription
    sizeofsizeof operator returns the size of a variable. For example sizeof(a), where a is integer, will return 4.
    Condition ? X : YConditional operator. If Condition is true ? then it returns value X : otherwise value Y
    ,Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.
    . (dot) and -> (arrow)Member operators are used to reference individual members of classes, structures, and unions.
    CastCasting operators convert one data type to another. For example, int(2.2000) would return 2.
    &Pointer operator & returns the address of an variable. For example &a; will give actual address of the variable.
    *Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.

    Operators Precedence in C++:

    Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
    For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 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.
    Show Examples
    Category Operator Associativity 
    Postfix () [] -> . ++ - -  Left to right 
    Unary + - ! ~ ++ - - (type)* & sizeof Right to left 
    Multiplicative  * / % Left to right 
    Additive  + - Left to right 
    Shift  << >> Left to right 
    Relational  < <= > >= Left to right 
    Equality  == != Left to right 
    Bitwise AND Left to right 
    Bitwise XOR Left to right 
    Bitwise OR Left to right 
    Logical AND && Left to right 
    Logical OR || Left to right 
    Conditional ?: Right to left 
    Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left 
    Comma Left to right

    C++ Loop Types

    There may be a situation when you need to execute a block of code several number of times. In general statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
    Programming languages provide various control structures that allow for more complicated execution paths.
    A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages:
    Loop Architecture
    C++ programming language provides following types of loop to handle looping requirements. Click the following links to check their detail.
    Loop TypeDescription
    while loopRepeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
    for loopExecute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
    do...while loopLike a while statement, except that it tests the condition at the end of the loop body
    nested loopsYou can use one or more loop inside any another while, for or do..while loop.

    Loop Control Statements:

    Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
    C++ supports the following control statements. Click the following links to check their detail.
    Control StatementDescription
    break statementTerminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
    continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
    goto statementTransfers control to the labeled statement. Though it is not advised to use goto statement in your program.

    The Infinite Loop:

    A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
    #include <iostream>
    using namespace std;
     
    int main ()
    {
    
       for( ; ; )
       {
          printf("This loop will run forever.\n");
       }
    
       return 0;
    }
    When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but C++ programmers more commonly use the for(;;) construct to signify an infinite loop.
    NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

    C++ Decision Making

    Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
    Following is the general from of a typical decision making structure found in most of the programming languages:
    C++ decision making
    C++ programming language provides following types of decision making statements. Click the following links to check their detail.
    StatementDescription
    if statementAn if statement consists of a boolean expression followed by one or more statements.
    if...else statementAn if statement can be followed by an optional else statement, which executes when the boolean expression is false.
    switch statementA switch statement allows a variable to be tested for equality against a list of values.
    nested if statementsYou can use one if or else if statement inside another if or else if statement(s).
    nested switch statementsYou can use one swicth statement inside another switch statement(s).

    The ? : Operator:

    We have covered conditional operator ? : in previous chapter which can be used to replace if...elsestatements. It has the following general form:
    Exp1 ? Exp2 : Exp3;
    Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
    The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

    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 so each function performs a specific task.
    A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
    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.
    A function is knows as with various names like a method or a sub-routine or a procedure etc.

    Defining a Function:

    The general form of a C++ function definition is as follows:
    return_type function_name( parameter list )
    {
       body of the function
    }
    A C++ function definition consists of a function header and a function body. Here are all the parts of a function:
    • Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
    • Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
    • Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
    • Function Body: The function body contains a collection of statements that define what the function does.

    Example:

    Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two:
    // function returning the max between two numbers
     
    int max(int num1, int num2) 
    {
       // local variable declaration
       int result;
     
       if (num1 > num2)
          result = num1;
       else
          result = num2;
     
       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.
    A function declaration has the following parts:
    return_type function_name( parameter list );
    For the above defined function max(), following is the function declaration:
    int max(int num1, int num2);
    Parameter names are not importan in function declaration only their type is required, so following is also valid declaration:
    int max(int, int);
    Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.

    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.
    When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
    To call a function you simply need to pass the required parameters along with function name and if function returns a value then you can store returned value. For example:
    #include <iostream>
    using namespace std;
     
    // function declaration
    int max(int num1, int num2);
     
    int main ()
    {
       // local variable declaration:
       int a = 100;
       int b = 200;
       int ret;
     
       // calling a function to get max value.
       ret = max(a, b);
     
       cout << "Max value is : " << ret << endl;
     
       return 0;
    }
     
    // function returning the max between two numbers
    int max(int num1, int num2) 
    {
       // local variable declaration
       int result;
     
       if (num1 > num2)
          result = num1;
       else
          result = num2;
     
       return result; 
    }
    I kept max() function along with main() function and complied the source code. While running final executable, it would produce following result:
    Max value is : 200

    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 parameters of 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:
    Call TypeDescription
    Call by valueThis 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.
    Call by pointerThis 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.
    Call by referenceThis method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
    By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.

    Default Values for Parameters:

    When you define a function you can specify a default value for for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.
    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>
    using namespace std;
     
    int sum(int a, int b=20)
    {
      int result;
    
      result = a + b;
      
      return (result);
    }
    
    int main ()
    {
       // local variable declaration:
       int a = 100;
       int b = 200;
       int result;
     
       // calling a function to add the values.
       result = sum(a, b);
       cout << "Total value is :" << result << endl;
    
       // calling a function again as follows.
       result = sum(a);
       cout << "Total value is :" << result << endl;
     
       return 0;
    }
    When the above code is compiled and executed, it produces following result:
    Total value is :300
    Total value is :120



    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.

    Defining Numbers in C++:

    You have already defined numbers in various examples given in previous chapters. Here is another consolidated example to define various types of numbers in C++:
    #include <iostream>
    using namespace std;
     
    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;
       cout << "short  s :" << s << endl;
       cout << "int    i :" << i << endl;
       cout << "long   l :" << l << endl;
       cout << "float  f :" << f << endl;
       cout << "double d :" << d << endl;
     
       return 0;
    }
    When the above code is compiled and executed, it produces following result:
    short  s :10
    int    i :1000
    long   l :1000000
    float  f :230.47
    double d :30949.4

    Math Operations in C++:

    In addition to the various functions you can create, C++ also includes some useful functions you can use. These functions are available in standard C and C++ libraries and called built-in functions. These are functions that can be included in your program and then use.
    C++ has a rich set of mathematical operations which can be performed on various numbers. Following table list down some useful built-in mathematical functions available in C++.
    To utilize these functions you need to include the math header file <cmath>.
    S.N.Function & Purpose
    1double cos(double);
    This function takes an angle (as a double) and returns the cosine.
    2double sin(double);
    This function takes an angle (as a double) and returns the sine.
    3double tan(double);
    This function takes an angle (as a double) and returns the tangent.
    4double log(double);
    This function takes a number and returns the natural log of that number.
    5double pow(double, double);
    The first is a number you wish to raise and the second is the power you wish to raise it to.
    6double 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.
    7double sqrt(double);
    You pass this function a number and it gives you this square root.
    8int abs(int);
    This function returns the absolute value of an integer that is passed to it.
    9double fabs(double);
    This function returns the absolute value of any decimal number passed to it.
    10double floor(double);
    Finds the integer which is less than or equal to the argument passed to it.
    Following a simple example to show few of the mathematical operations:
    #include <iostream>
    #include <cmath>
    using namespace std;
     
    int main ()
    {
       // number definition:
       short  s = 10;
       int    i = -1000;
       long   l = 100000;
       float  f = 230.47;
       double d = 200.374;
    
       // mathematical operations;
       cout << "sin(d) :" << sin(d) << endl;
       cout << "abs(i)  :" << abs(i) << endl;
       cout << "floor(d) :" << floor(d) << endl;
       cout << "sqrt(f) :" << sqrt(f) << endl;
       cout << "pow( d, 2) :" << pow(d, 2) << endl;
     
       return 0;
    }
    When the above code is compiled and executed, it produces following result:
    sign(d) :-0.634939
    abs(i)  :1000
    floor(d) :200
    sqrt(f) :15.1812
    pow( d, 2 ) :40149.7

    Random Numbers in C++:

    There are many cases where you will wish to generate a random number. There are actually two functions you will need to know about random number generation. The first is rand(), this function will only return a pseudo random number. The way to fix this is to first call the srand() function.
    Following a simple example to generate few random numbers. This example makes use of time()function to get the number of seconds on your system time, to randomly seed the rand() function:
    #include <iostream>
    #include <ctime>
    
    using namespace std;
     
    int main ()
    {
       int i,j;
     
       // set the seed
       srand( (unsigned)time( NULL ) );
    
       /* generate 10  random numbers. */
       for( i = 0; i < 10; i++ )
       {
          // generate actual random number
          j= rand();
          cout <<" Random Number : " << j << endl;
       }
    
       return 0;
    }
    When the above code is compiled and executed, it produces 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 



    C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
    Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
    All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

    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:
    type arrayName [ arraySize ];
    This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double, use this statement:
    double balance[10];

    Initializing Arrays:

    You can initialize C++ array elements either one by one or using a single statement as follows:
    double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
    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:
    double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
    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 ie. 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:
    Array Presentation

    Accessing Array Elements:

    An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:
    double salary = balance[9];
    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>
    using namespace std;
     
    #include <iomanip>
    using std::setw;
     
    int main ()
    {
       int n[ 10 ]; // n is an array of 10 integers
     
       // initialize elements of array n to 0          
       for ( int i = 0; i < 10; i++ )
       {
          n[ i ] = i + 100; // set element at location i to i + 100
       }
       cout << "Element" << setw( 13 ) << "Value" << endl;
     
       // output each array element's value                      
       for ( int j = 0; j < 10; j++ )
       {
          cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
       }
     
       return 0;
    }
    This program makes use setw() function to format the output. When the above code is compiled and executed, it produces following result:
    Element        Value
          0          100
          1          101
          2          102
          3          103
          4          104
          5          105
          6          106
          7          107
          8          108
          9          109

    C++ Arrays in Detail:

    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:
    ConceptDescription
    Multi-dimensional arraysC++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
    Pointer to an arrayYou can generate a pointer to the first element of an array by simply specifying the array name, without any index.
    Passing arrays to functionsYou can pass to the function a pointer to an array by specifying the array's name without an index.
    Return array from functionsC++ allows a function to return an array.

    C++ Strings 

    C++ provides following two types of string representations:
    • The C-style character string.
    • The string class type introduced with Standard C++.

    The C-Style Character String:

    The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a nullcharacter '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
    The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
    char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    If you follow the rule of array initialization then you can write the above statement as follows:
    char greeting[] = "Hello";
    Following is the memory presentation of above defined string in C/C++:
    String Presentation in C/C++
    Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above mentioned string:
    #include <iostream>
    
    using namespace std;
    
    int main ()
    {
       char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
    
       cout << "Greeting message: ";
       cout << greeting << endl;
    
       return 0;
    }
    When the above code is compiled and executed, it produces result something as follows:
    Greeting message: Hello
    C++ supports a wide range of functions that manipulate null-terminated strings:
    S.N.Function & Purpose
    1strcpy(s1, s2);
    Copies string s2 into string s1.
    2strcat(s1, s2);
    Concatenates string s2 onto the end of string s1.
    3strlen(s1);
    Returns the length of string s1.
    4strcmp(s1, s2);
    Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
    5strchr(s1, ch);
    Returns a pointer to the first occurrence of character ch in string s1.
    6strstr(s1, s2);
    Returns a pointer to the first occurrence of string s2 in string s1.
    Following example makes use of few of the above mentioned functions:
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    int main ()
    {
       char str1[10] = "Hello";
       char str2[10] = "World";
       char str3[10];
       int  len ;
    
       // copy str1 into str3
       strcpy( str3, str1);
       cout << "strcpy( str3, str1) : " << str3 << endl;
    
       // concatenates str1 and str2
       strcat( str1, str2);
       cout << "strcat( str1, str2): " << str1 << endl;
    
       // total lenghth of str1 after concatenation
       len = strlen(str1);
       cout << "strlen(str1) : " << len << endl;
    
       return 0;
    }
    When the above code is compiled and executed, it produces result something as follows:
    strcpy( str3, str1) : Hello
    strcat( str1, str2): HelloWorld
    strlen(str1) : 10

    The String Class in C++:

    The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. We will study this class in C++ Standard Library but for now let us check following example:
    At this point you may not understand this example because so far we have not discussed Classes and Objects. So can have a look and proceed until you have understanding on Object Oriented Concepts.
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main ()
    {
       string str1 = "Hello";
       string str2 = "World";
       string str3;
       int  len ;
    
       // copy str1 into str3
       str3 = str1;
       cout << "str3 : " << str3 << endl;
    
       // concatenates str1 and str2
       str3 = str1 + str2;
       cout << "str1 + str2 : " << str3 << endl;
    
       // total lenghth of str3 after concatenation
       len = str3.size();
       cout << "str3.size() :  " << len << endl;
    
       return 0;
    }
    When the above code is compiled and executed, it produces result something as follows:
    str3 : Hello
    str1 + str2 : HelloWorld
    str3.size() :  10




    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.
    As you know every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator which denotes an address in memory. Consider the following which will print the address of the variables defined:
    #include <iostream>
    
    using namespace std;
    
    int main ()
    {
       int  var1;
       char var2[10];
    
       cout << "Address of var1 variable: ";
       cout << &var1 << endl;
    
       cout << "Address of var2 variable: ";
       cout << &var2 << endl;
    
       return 0;
    }
    When the above code is compiled and executed, it produces result something as follows:
    Address of var1 variable: 0xbfebd5c0
    Address of var2 variable: 0xbfebd5b6

    What Are Pointers?

    pointer is a variable whose value is the address of another variable. Like any variable or constant, you must declare a pointer before you can work with it. The general form of a pointer variable declaration is:
    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:
    int    *ip;    // pointer to an integer
    double *dp;    // pointer to a double
    float  *fp;    // pointer to a float
    char   *ch     // pointer to character
    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.

    Using Pointers in C++:

    There are few important operations which we will do with the pointers very frequently. (a) we define a pointer variables (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Following example makes use of these operations:
    #include <iostream>
    
    using namespace std;
    
    int main ()
    {
       int  var = 20;   // actual variable declaration.
       int  *ip;        // pointer variable 
    
       ip = &var;       // store address of var in pointer variable
    
       cout << "Value of var variable: ";
       cout << var << endl;
    
       // print the address stored in ip pointer variable
       cout << "Address stored in ip variable: ";
       cout << ip << endl;
    
       // access the value at the address available in pointer
       cout << "Value of *ip variable: ";
       cout << *ip << endl;
    
       return 0;
    }
    When the above code is compiled and executed, it produces result something as follows:
    Value of var variable: 20
    Address stored in ip variable: 0xbfc601ac
    Value of *ip variable: 20

    C++ Pointers in Detail:

    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:
    ConceptDescription
    C++ Null PointersC++ supports null pointer, which is a constant with a value of zero defined in several standard libraries.
    C++ pointer arithmeticThere are four arithmetic operators that can be used on pointers: ++, --, +, -
    C++ pointers vs arraysThere is a close relationship between pointers and arrays. Let us check how?
    C++ array of pointersYou can define arrays to hold a number of pointers.
    C++ pointer to pointerC++ allows you to have pointer on a pointer and so on.
    Passing pointers to functionsPassing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.
    Return pointer from functionsC++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.

    C++ References

    A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.

    C++ References vs Pointers:

    References are often confused with pointers but three major differences between references and pointers are:
    • You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.
    • Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.
    • A reference must be initialized when it is created. Pointers can be initialized at any time.

    Creating References in C++:

    Think of a variable name as a label attached to the variable's location in memory. You can then think of a reference as a second label attached to that memory location. Therefore, you can access the contents of the variable through either the original variable name or the reference. For example, suppose we have the following example:
    int    i = 17;
    We can declare reference variables for i as follows.
    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>
     
    using namespace std;
     
    int main ()
    {
       // declare simple variables
       int    i;
       double d;
     
       // declare reference variables
       int&    r = i;
       double& s = d;
       
       i = 5;
       cout << "Value of i : " << i << endl;
       cout << "Value of i reference : " << r  << endl;
     
       d = 11.7;
       cout << "Value of d : " << d << endl;
       cout << "Value of d reference : " << s  << endl;
       
       return 0;
    }
    When the above code is compiled together and executed, it produces 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:
    ConceptDescription
    References as parametersC++ supports passing references as function parameter more safely than parameters.
    Reference as return valueYou can return reference from a C++ function like a any other data type can be returned.

No comments:

Post a Comment