Author: admin

  • C++ Basic Input/Output

    The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming.

    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.

    I/O Library Header Files

    There are following header files important to C++ programs −

    Sr.NoHeader File & Function and Description
    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>This file declares services for user-controlled file processing. We will discuss about it in detail in File and Stream related chapter.
    4<bits/stdc++.h>This header file includes most of the standard C++ libraries, which adds a wide range of functionalities without the need to specify each library individually. This is particularly helpful during coding contests.

    The Standard Output Stream (cout)

    The predefined object cout is an instance of ostream class. The cout object is said to be “connected to” the standard output device, which usually is the display screen. The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs as shown in the following example.

    Example

    #include <iostream>usingnamespace std;intmain(){char str[]="Hello C++";
     
       cout <<"Value of str is : "<< str << endl;}

    When the above code is compiled and executed, it produces the following result −

    Value of str is : Hello C++
    

    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.

    The Standard Input Stream (cin)

    The predefined object cin is an instance of istream class. The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs as shown in the following example.

    Example

    #include <iostream>usingnamespace std;intmain(){char name[50];
     
       cout <<"Please enter your name: ";
       cin >> name;
       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 −

    Please enter your name: cplusplus
    Your name is: cplusplus
    

    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 −

    cin >> name >> age;
    

    This will be equivalent to the following two statements −

    cin >> name;
    cin >> age;
    

    The Standard Error Stream (cerr)

    The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the standard error device, which is also a display screen but the object cerr is un-buffered and each stream insertion to cerr causes its output to appear immediately.

    The cerr is also used in conjunction with the stream insertion operator as shown in the following example.

    Example

    #include <iostream>usingnamespace std;intmain(){char str[]="Unable to read....";
     
       cerr <<"Error message : "<< str << endl;}

    When the above code is compiled and executed, it produces the following result −

    Error message : Unable to read....
    

    The Standard Log Stream (clog)

    The predefined object clog is an instance of ostream class. The clog object is said to be attached to the standard error device, which is also a display screen but the object clog is buffered. This means that each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the buffer is flushed.

    The clog is also used in conjunction with the stream insertion operator as shown in the following example.

    Example

    #include <iostream>usingnamespace std;intmain(){char str[]="Unable to read....";
     
       clog <<"Error message : "<< str << endl;}

    When the above code is compiled and executed, it produces the following result −

    Error message : Unable to read....
    

    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.

    Input/Output Using bits/stdc++

    The bits/stdc++.h is a non-standard header file in C++, as it does not belong to the official C++ Standard Library. Instead, it is a GCC-specific header file that includes most of the standard libraries in C++. You can also use bits/stdc++.h for the input and output without using another library.

    Example

    #include <bits/stdc++.h>usingnamespace std;intmain(){int number;
      string name;// #include <iostream>// #include <string>
      cout <<"Welcome to TutorialsPoint!"<< endl;// Input of user's name and number
      cout <<"Please enter your name: ";
      cin >> name;
      cout <<"Please enter a number: ";
      cin >> number;
      cout <<"Hello,"<< name <<" You entered "<< number << endl;// Demonstrating some STL features// #include <vector>
      vector<int> numbers;
      cout <<"Enter 4 numbers: ";for(int i =0; i <4;++i){int temp;
        cin >> temp;
        numbers.push_back(temp);}
      cout <<"You entered the following numbers: ";for(int num : numbers){
        cout << num <<" ";}
      cout << endl;// Sort and display the numbers// #include <algorithm>sort(numbers.begin(), numbers.end());
      cout <<"Sorted numbers: ";for(int num : numbers){
        cout << num <<" ";}
      cout << endl;return0;}

    When the above code is compiled and executed, it produces the following result −

    Welcome to TutorialsPoint!
    Please enter your name: Aman
    Please enter a number: 2006
    Hello, Aman You 2006
    Enter 4 numbers: 2
    0
    0
    6
    You entered the following numbers: 2 0 0 6 
    Sorted numbers: 0 0 2 6
    

    So here, instead of using these multiple headers such as,

    • #include <iostream>
    • #include <string>
    • #include <vector>
    • #include <algorithm>

    We used simply <bits/stdc++.h> as it includes all the necessary standard libraries for input/output operations, string handling, dynamic arrays, and algorithms which simplifies your code and makes it cleaner and more convenient. It is especially used for competitive programming.

  • C++ Declare Multiple Variables

    C++ programming language allows programmers to declare multiple variables in a single statement without any line breaks. This is only possible for variables which belong to the same data type.

    How to Declare Multiple Variables in C++?

    This is executed using a comma (,) separated list of variables with different variables names, and the data types must be the same for all variables to be declared. Multiple variables declaration is supported for all data types in C++, for example, we can declare multiple strings with different names in a single statement using a comma separated list.

    Syntax

    The following syntax shows how to declare multiple variables with same data types in a single statement −

    data_type var_a, var_b, var_;

    Example

    The following exemplar code shows how to declare multiple variables with same data types in a single statement −

    #include <iostream>usingnamespace std;intmain(){int y,z,x;
    
       x=10;
       y=20;
       z=30;
    
       cout<<"value of x: "<<x<<endl<<"value of y: "<<y<<endl<<"value of z: "<<z;return0;}

    Output

    value of x: 10
    value of y: 20
    value of z: 30
    

    Initialize Multiple Variables

    The variables can also be initialized with different values in the same statement of declaration, which makes it easy to declare variables of different values.

    Syntax

    The following syntax shows how to declare multiple variables, and initialize them with values in a single statement −

    data_type var_a=[value1], var_b, var_c=[value3];

    Here, var_a, var_b and var_c are variables of same data type, and [value] is the value of that variable.

    Example

    The following exemplar code shows how to declare multiple variables, and initialize them with values in a single statement −

    #include <iostream>usingnamespace std;intmain(){int y=10,z=20,x;
       x=10;
       cout<<"value of x: "<<x<<endl<<"value of y: "<<y<<endl<<"value of z: "<<z;return0;}

    Output

    value of x: 10
    value of y: 10
    value of z: 20
    

    Initialize Multiple Variables with Same Value

    The variables can also be initialized with the same values in a single statement using the “=” operator multiple times in a single statement.

    Syntax

    The following syntax shows how to declare multiple variables and initialize all of them to a single value in a single statement −

    data_type var_1, var_2, var_3;
    var_1=var_2=var_3=[value]

    Here, the variables var_1, var_2 and var_3 are initialized to a single value [value] in a single statement.

    Example

    The following exemplar code shows how to declare multiple variables and initialize all of them to a single value in a single statement −

    #include <iostream>usingnamespace std;intmain(){int y,z;int x=y=z=10;
       cout<<"value of x: "<<x<<endl<<"value of y: "<<y<<endl<<"value of z: "<<z;return0;}

    Output

    value of x: 10
    value of y: 10
    value of z: 10
  • Variable Scope in C++

    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++ variables scopes are categorized mainly two parts −

    • Local Variables
    • 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.

    C++ Variable Scopes

    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.

    Example

    Following is the example using local variables −

    #include <iostream>usingnamespace std;intmain(){// Local variable declarationint a, b;int c;// actual initialization
       a =10;
       b =20;
       c = a + b;
     
       cout << c;return0;}

    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.

    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.

    Example

    Following is the example using global and local variables −

    #include <iostream>usingnamespace std;// Global variable declarationint g;intmain(){// Local variable declarationint a, b;// actual initialization
       a =10;
       b =20;
       g = a + b;
      
       cout << g;return0;}

    Local and Global Variables with Same Names

    A program can have same name for local and global variables but value of local variable inside a function will take preference.

    Example

    #include <iostream>usingnamespace std;// Global variable declarationint g =20;intmain(){// Local variable declarationint g =10;
     
       cout << g;return0;}

    When the above code is compiled and executed, it produces the following result −

    10
    

    Accessing Global Variable

    You can access a global variable when there is a local variable with the same name by using the SRO (Scope Resolution Operator) :: before the name of that variable.

    Example

    In the following example, we have global and local variables with the same name, and accessing and printing the value of the global variable −

    #include <iostream>usingnamespace std;// Global variable declaration:int g =20;intmain(){// Local variable declaration:int g =10;
    
       cout <<"Value of g (Local variable): "<< g;
       cout << endl;
       
       cout <<"Value of g (Global variable): "<<::g;return0;}

    When the above code is compiled and executed, it produces the following result −

    Value of g (Local variable): 10
    Value of g (Global variable): 20
    

    Initializing Local and Global Variables

    When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows −

    Data TypeInitializer
    int0
    char‘\0’
    float0
    double0
    pointerNULL

    It is a good programming practice to initialize variables properly, otherwise sometimes program would produce unexpected result.

  • C++ Variables and Types

    C++ Variable

    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.

    C++ Variable Naming

    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.

    Some other rules for variable naming conventions in C++ −

    • Keywords cannot be used as variable names.
    • The variable name cannot contain spaces.
    • Hyphen (-) cannot be used within the variable names.
    • Variable names must not start with special characters and numbers. It should be either an uppercase or lowercase character or an underscore (_).

    Example of Valid Variable Names

    Some of the valid variable names are −

    int age;int _age;int student_age;int studentAge;

    Example of Invalid Variable Names

    Some of the invalid variable names are −

    int2ndvariable;int student-age;intfloat;int student age;int #age;

    Types of C++ Variables

    There are following basic types of variable in C++ as explained in last chapter −

    Sr.NoType & Description
    1boolStores either value true or false.
    2charTypically a single octet (one byte). This is an integer type.
    3intThe most natural size of integer for the machine.
    4floatA single-precision floating point value.
    5doubleA double-precision floating point value.
    6voidRepresents the absence of type.
    7wchar_tA wide character type.

    C++ also allows to define various other types 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 types of variables.

    Variable Definition in C++

    A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type, and contains a list of one or more variables of that type as follows −

    Syntax

    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.

    Variable Initialization in C++

    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 −

    Syntax

    type variable_name = value;

    Example

    Some examples are −

    externint d =3, f =5;// declaration of d and f. int d =3, f =5;// definition and initializing d and f. 
    byte z =22;// definition and initializes z. char x ='x';// the variable x has the value 'x'.

    For definition 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.

    Variable Declaration in C++

    A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable definition at the time of linking of the program.

    A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use extern keyword to declare a variable at any place. Though you can declare a variable multiple times in your C++ program, but it can be defined only once in a file, a function or a block of code.

    Example

    Try the following example where a variable has been declared at the top, but it has been defined inside the main function −

    #include <iostream>usingnamespace std;// Variable declaration:externint a, b;externint c;externfloat f;intmain(){// Variable definition: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 ;return0;}

    When the above code is compiled and executed, it produces the following result −

    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 declarationintfunc();intmain(){// function callint i =func();}// function definitionintfunc(){return0;}

    Lvalues and Rvalues

    There are two kinds of expressions in C++ −

    • lvalue − Expressions that refer to a memory location is called “lvalue” expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.
    • rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means 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 the following is not a valid statement and would generate compile-time error −

    10 = 20;

  • C++ Boolean (bool) Data Type

    The bool data type in C++ stands for Boolean values, which are True and False. In C++, 1 stands for True whereas 0 stands for False. The keyword “bool” is used to declare a Boolean data type. The addition of bool data type is a one of the newer features of C++ language.

    Use of Boolean Data Type

    The Boolean (bool) data type is used in the following ways −

    • In conditions where we need to have binary values, i.e., values which represent two states of a variable.
    • When we need to run loops based on certain conditions, we use bool data types.
    • In case of having null values, we generally relate them to bool data types.
    • For comparing two values for equality or inequality, we generally use bool data types.

    Values of Boolean (bool) Data Type

    The bool data types in C++ can have one of two values, and these values are as follows −

    • True or 1
    • False or 0

    As stated earlier, Boolean 1 means true whereas Boolean 0 means false in C++ compilation.

    Creating a Boolean Variable

    We can declare a Boolean variable using the “bool” keyword followed by the variable name.

    Syntax

    Use the following syntax to create a Boolean type variable −

    bool variable_name =[value];

    Here, [value] is an optional and can be used to assign value during the declaration.

    Example

    In the following examples, we are declaring a Boolean variable, assigning a value to it.

    // C++ program to demonstrate // bool data type #include <iostream> usingnamespace std;// Driver code intmain(){bool flag;
       flag=1;//this is true    
       cout<<flag;return0;}

    Example of bool Data Type

    The following example demonstrate the use of Boolean (bool) data type −

    // C++ program to demonstrate// bool data type#include <iostream>usingnamespace std;intmain(){bool flag;
       flag=1;//this is truebool flag1=true;
    
       cout<<flag<<" "<<flag1<<endl;int count=0;while(flag){//condition where flag is true
          count++;if(count>=3) flag=false;}
    
       cout<<count<<" "<<flag<<endl;if(flag1) cout<<"True flag1"<<endl;else cout<<"False flag1"<<endl;return0;}

    Output

    1 1
    3 0
    True flag1
    

    Implicit Conversion of Bool Variables

    Boolean data types can be implicitly converted to numeric data types, and vice-versa. This is possible as any value greater than 0 has a Boolean true value, whereas any value less than or equal to 0 has a Boolean false value.

    Also, the Boolean values can be added in form of integers to integral variables, using implicit conversion techniques. Hence, when we add a Boolean value to an integer, it gets incremented by 1 if the value is true, otherwise it remains same as false value corresponds to 0.

    Example

    This is clearly explained in the examples given below −

    // C++ program to demonstrate
    // bool data type
    #include <iostream>
    using namespace std;

    int main() {
    bool flag;
    flag=1;//this is true
    bool flag1=true;

    cout<<flag<<" "<<flag1<<endl;

    int count=0;
    int x=12;
    float y=35.45;
    bool k=count, k1=x, k2=y;
    int sum=x+flag+flag1;

    cout<<k<<" "<<count<<" "<<k1<<" "<<x<<" "<<k2<<" "<<y<<" "<<endl;
    cout<<After adding Boolean and integer values : << sum<<endl;
    return 0;
    }
  • C++ Character (char) Data Type

    The character (char) data type in C++ stands for alphanumeric values, which can be a wide range of characters. These may include alphabets like ‘a’, ‘b’, and ‘c’, numeric values like ‘1’, ‘2’, and ‘3’, symbols like ‘#’, ‘$’, and ‘&’, and many more.

    The character data type takes 1 Byte (i.e., 8 bits) of memory space to store characters. In C++, the keyword “char” is used to declare a character variable.

    In this tutorial, we will explore more about character data type, and its corresponding variables.

    Use Character (char) Data Type

    The following are some of the uses of character (char) data type −

    • The char data type is used when we need to hold only a single character and do not need the overhead of String.
    • The char data type can also be used in primitive form as an array without the use of a string literal.
    • In ASCII form, char data type can be used to represent numeric values and vice-versa.

    Values of char Data Type

    The character (char) data type in C++ can have multiple values, and these values are as follows −

    • Uppercase Alphabets, like A, B, Z, etc.
    • Lowercase Alphabets, like a, b, z, etc.
    • Symbols, like $, %, &, etc.
    • Escape Sequences, which will be discussed later in this article.

    Creating a Character (char) Variable

    We can declare a character variable using the “char” keyword followed by the variable name.

    Syntax

    Use the following syntax to create a char type variable −

    char variable_name =[value];

    Here, [value] is an optional and can be used to assign value during the declaration.

    Example

    In the following example, we are declaring a char variable, assigning a value to it.

    // C++ program to demonstrate// Character data type#include <iostream> usingnamespace std;intmain(){char ch;return0;}

    Example of Character (char) Data Type

    The following example shows the use of different character data types −

    // C++ program to demonstrate// Character data type#include <iostream>usingnamespace std;intmain(){char ch,ch1,ch2;
       ch='a';//this is an alphabet
       ch1='&';//this is a symbol
       ch2='1';//this is a number
       cout<<ch<<endl<<ch1<<endl<<ch2<<endl;return0;}

    Output

    a
    &
    1
    

    ASCII Values of Characters

    ASCII stands for the “American Standard Code for Information Interchange”. It was the first set of encoding values assigned to different characters and symbols. The character sets used in modern computers, in HTML, and on the Internet, are all based on ASCII.

    The ASCII table describes a numeric value for all character types, and these values can be used to declare a character without the explicit use of the character itself. It contains the numbers from 0-9, the upper and lower case English letters from A to Z, and some special characters.

    The following data gives a reference for all ASCII values of characters available in C++ −

    ASCII Range of 'a' to 'z'=97-122
    ASCII Range of 'A' to 'Z'=65-90
    ASCII Range of '0' to '9'=48-57

    Example to Show ASCII Declaration

    The following example shows how a user can declare a character variable using ASCII values, without explicit usage of the character itself −

    #include <iostream>usingnamespace std;intmain(){char ch,ch1,ch2;
       ch=65;//this is an alphabet
       ch1=45;//this is a symbol
       ch2=55;//this is a number
       cout<<ch<<endl<<ch1<<endl<<ch2<<endl;return0;}

    Output

    A
    -
    7
    

    Implicit Conversion of Character Variables

    Character variables can be implicitly converted to their integer values using ASCII references, and vice-versa. Hence, when we declare a character in C++, we can reference their ASCII value, whereas an ASCII numerical can be used to access its character value as well. This is done using implicit conversion or typecasting of data types.

    We can add a keyword of the data type we need to convert the given variable into, and the compiler changes the data type automatically. For example, if we write char(97), it will load the character value of ASCII number 97, which is ‘a’. This is also possible for converting the character data type to integral (ASCII) values.

    This is clearly explained in the examples given below −

    Example

    The following example shows the implicit typecasting of char to int, and vice-versa −

    #include <iostream>usingnamespace std;intmain(){char c ='$';int a =97;
       cout <<"The Corresponding ASCII value of '$' : ";
       cout <<int(c)<< endl;
    
       cout <<"The Corresponding  character value of 97 : ";
       cout <<char(a)<< endl;return0;}

    Output

    The Corresponding ASCII value of '$' : 36
    The Corresponding  character value of 97 : a
    

    ESCAPE SEQUENCE IN C++

    Character variables which begin with a backslash (“\”) are called escape sequences. These determine on the output sequence on the output window of a compiler. In this context, backslash is also called as the ‘Escape Character’.

    The following table shows different types of escape sequences available in C++ −

    S. No.Escape SequencesCharacter
    1.\nNewline
    2.\\Backslash
    3.\tHorizontal Tab
    4.\vVertical Tab
    5.\0Null Character

    The usage of escape sequences is clearly explained in the following example code −

    Example 1

    #include <iostream>usingnamespace std;intmain(){char a ='H';char b ='E';char c ='Y';char d ='\n';//enter new linechar e ='\t';//tab to enter space 
       cout << a << b << c << d << a << b << c << e << a << b << c;return0;}

    Output

    HEY	HEYHEY
    HEY	HEY
    

    The escape character can also be used to insert special characters into strings. This is clearly explained in the example given below −

    Example 2

    #include <iostream>usingnamespace std;intmain(){//string txt = "Hey, where are you "vikas" ? ";//this throws error
       string txt ="Hey, where are you \"vikas\"? ";
    
       cout<<txt<<endl;return0;}

    Output

    Hey, where are you "vikas"? 
  • C++ Numeric Data Types

    Numeric data types in C++ are used to handle numerical data like integers (both signed and unsigned), floating-point values, and precision values.

    Numeric data types mainly contain three fundamental types of numeric data, which are as follows −

    • Int
      • Int
      • Short Int
      • Long Int
      • Long Long Int
      • Unsigned Int
      • Unsigned Short Int
      • Unsigned Long Int
      • Unsigned Long Long Int
    • Float
    • Double
    • Long Double

    In this article, we will go through all of the numeric data types and their subtypes in detail with examples.

    int Data Type

    The int data type is short for integer, which takes numeric values from -231 to (231-1). It takes 4 Bytes (i.e., 32 bits) in the memory.

    Syntax

    int variable_name;

    It is further classified into various derived subtypes, which are as follows −

    (a) short int

    The short int is used for smaller numbers, as it takes only 2 Bytes (i.e., 16 bits) in the memory. It’s value ranges from -215to (215-1).

    Syntax

    shortint varianle_name;

    (b) long int

    The long int is used for bigger numbers, with memory space of 4 bytes (i.e., 32 bits), and can be up to 8 bytes (i.e., 64 bits), depending upon the compiler.

    Syntax

    longint variable_name;

    (c) long long int

    The long long int is used for larger numbers, with memory space of 8 bytes (i.e. 64 bits), and can be up to 16 bytes (i.e., 128 bits), depending upon the compiler. It’s value ranges from -263 to (263-1).

    Syntax

    longlongint variable_name;

    (d) unsigned int

    The unsigned int is used to store only non-negative value, and take up same memory space as an int data type, which is 4 Bytes (i.e. 32 bits). It’s value ranges from 0 to (232-1).

    Syntax

    unsignedint variable_name;

    (e) unsigned short int

    The unsigned short int is used to store only non-negative value, and take up same memory space as a short int data type, which is 2 Bytes (i.e., 16 bits). It’s value ranges from 0 to (216-1).

    Syntax

    unsignedshortint variable_name;

    (f) unsigned long int

    The unsigned long int is used to store only non-negative value, and take up same memory space as a long int data type, which ranges from 4 Bytes (i.e., 32 bits) to 8 Bytes (i.e., 64 bits).

    Syntax

    unsignedlongint variable_name;

    (g) unsigned long long int

    The unsigned long long int is used to store only non-negative value, and take up same memory space as a long long int data type, which ranges from 8 Bytes (i.e., 32 bits) to 16 Bytes (128 bits). It’s value ranges from 0 to (264-1).

    Syntax

    unsignedlonglongint variable_name;

    Example of int Data Type

    The following code shows the size and use of all derived int data types −

    #include <iostream>usingnamespace std;intmain(){int a=16;shortint b=3;longint c=-32;longlongint d=555;unsignedshortint e=22;unsignedint f=33;unsignedlongint g=888;unsignedlonglongint h=444444;
    
       cout <<"sizeof int datatype is: "<<sizeof(a)<<" and the number is: "<<a<< endl; 
    
       cout <<"sizeof short int datatype is: "<<sizeof(unsignedint)<<" and the number is: "<<b<<  endl; 
    
       cout <<"sizeof long int datatype is: "<<sizeof(shortint)<<" and the number is: "<<c<<  endl; 
    
       cout <<"sizeof long long int datatype is: "<<sizeof(unsignedshortint)<<" and the number is: "<<d<<  endl; 
    
       cout <<"sizeof unsigned short int datatype is: "<<sizeof(longint)<<" and the number is: "<<e<<  endl; 
    
       cout <<"sizeof unsigned int datatype is: "<<sizeof(unsignedlongint)<<" and the number is: "<<f<<  endl; 
    
       cout <<"sizeof unsigned long int datatype is: "<<sizeof(longlongint)<<" and the number is: "<<g<<  endl; 
    
       cout <<"sizeof unsigned long long int datatype is: "<<sizeof(unsignedlonglongint)<<" and the number is: "<<h<<  endl;return0;}

    Output

    sizeof int datatype is: 4 and the number is: 16
    sizeof short int datatype is: 4 and the number is: 3
    sizeof long int datatype is: 2 and the number is: -32
    sizeof long long int datatype is: 2 and the number is: 555
    sizeof unsigned short int datatype is: 8 and the number is: 22
    sizeof unsigned int datatype is: 8 and the number is: 33
    sizeof unsigned long int datatype is: 8 and the number is: 888
    sizeof unsigned long long int datatype is: 8 and the number is: 444444
    

    float Data Type

    The float data type is used for floating-point elements, which are numbers that are followed by a decimal part. This data type takes 4 Bytes (i.e., 32 bits) of memory.

    Syntax

    float elem_name;

    Example of float Data Type

    The following code shows the size and use of all derived int data types −

    #include <bits/stdc++.h>usingnamespace std;intmain(){float k=1.120123;
       cout <<"sizeof float datatype is: "<<sizeof(k)<<" and the element is: "<<k<<endl;return0;}

    Output

    sizeof float datatype is: 4 and the element is: 1.12012
    

    double Data Type

    The double data type is used to store floating-point elements with double precision as compared to float. This data type takes 8 Bytes (i.e., 64 bits) of memory.

    Syntax

    double elem_name;

    The double data type has a further categorization which takes up more memory and stores more precise elements.

    long double

    Another data type derived from double is long double, which takes 16 Bytes (i.e., 128 bits) of memory space.

    Syntax

    double elem_name;

    Example

    The following code shows the size and use of all derived int data types −

    #include <bits/stdc++.h>usingnamespace std;intmain(){double m=1.34000123;longdouble n=1.21312312421;
    
       cout <<"sizeof double datatype is: "<<sizeof(m)<<" and the element is: "<<m<<endl; 
       cout <<"sizeof long double datatype is: "<<sizeof(n)<<" and the element is: "<<n<<endl;return0;}
    Output
    sizeof double datatype is: 8 and the element is: 1.34
    sizeof long double datatype is: 16 and the element is: 1.21312
    

    Explicit Conversion of Numeric Data Types

    In C++, the explicit type conversion is not done automatically, you need to convert the type manually by placing the target data type in the parentheses (). It tells the compiler to convert the value of a variable or an expression to a specific (target) data type.

    Example

    The following program shows the explicit conversion of numeric data types from one to another −

    #include <bits/stdc++.h>usingnamespace std;intmain(){double a=6.551555; 
       cout<<"value of a (int) is "<<(int)a<<endl;
       cout<<"value of a (float) is "<<(float)a<<endl;
       cout<<"value of a (double) is "<<a<<endl;
       cout<<"Value of a (long double) is "<<(longdouble)a;return0;}

    Output

    value of a (int) is 6
    value of a (float) is 6.55156
    value of a (double) is 6.55155
    Value of a (long double) is 6.55155
  • C++ Data Types

    While writing program in any 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 types 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++ offers the programmer a rich assortment of built-in as well as user defined data types. Following table lists 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 in memory, and what is maximum and minimum value 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 int2bytes0 to 65,535
    signed short int2bytes-32768 to 32767
    long int8bytes-9223372036854775808 to 9223372036854775807
    signed long int8bytessame as long int
    unsigned long int8bytes0 to 18446744073709551615
    long long int8bytes-(2^63) to (2^63)-1
    unsigned long long int8bytes0 to 18,446,744,073,709,551,615
    float4bytes
    double8bytes
    long double12bytes
    wchar_t2 or 4 bytes1 wide character

    The size of variables might be different from those shown in the above table, depending on the compiler and the computer you are using.

    Example

    Following is the example, which will produce correct size of various data types on your computer.

    #include <iostream>usingnamespace std;intmain(){
       cout <<"Size of char : "<<sizeof(char)<< endl;
       cout <<"Size of int : "<<sizeof(int)<< endl;
       cout <<"Size of short int : "<<sizeof(shortint)<< endl;
       cout <<"Size of long int : "<<sizeof(longint)<< endl;
       cout <<"Size of float : "<<sizeof(float)<< endl;
       cout <<"Size of double : "<<sizeof(double)<< endl;
       cout <<"Size of wchar_t : "<<sizeof(wchar_t)<< endl;return0;}

    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() operator to get size of various data types.

    When the above code is compiled and executed, it produces the 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
    

    Example

    Following is another example:

    #include <iostream>#include <limits>usingnamespace std;intmain(){
    
        std::cout <<"Int Min "<< std::numeric_limits<int>::min()<< endl;
        std::cout <<"Int Max "<< std::numeric_limits<int>::max()<< endl;
        std::cout <<"Unsigned Int  Min "<< std::numeric_limits<unsignedint>::min()<< endl;
        std::cout <<"Unsigned Int Max "<< std::numeric_limits<unsignedint>::max()<< endl;
        std::cout <<"Long Int Min "<< std::numeric_limits<longint>::min()<< endl;
        std::cout <<"Long Int Max "<< std::numeric_limits<longint>::max()<< endl;
    
        std::cout <<"Unsigned Long Int Min "<< std::numeric_limits<unsignedlongint>::min()<<endl;
        std::cout <<"Unsigned Long Int Max "<< std::numeric_limits<unsignedlongint>::max()<< endl;}

    Derived Data Types

    Data types which are obtained from pre-defined data types in C++ are known as Derived Data Types. These can be classified into four categories, namely −

    1. Function

    function is the simplest form of user-defined data type. It includes a return type, a function name and input parameters.

    Syntax

    return_type function_name(input_param1, input_param2){<function_body>}

    Example

    #include <iostream>usingnamespace std;
    
    string func(int n){//returns if n is odd or evenif(n%2)return"Given number is Odd !";elsereturn"Given number is Even !";}intmain(){int a;//enter a number
       cin>>a;
       cout<<func(a);//a simple function to check if//number is odd or evenreturn0;}
    Output
    Given number is Even !
    

    2. Array

    An array is a series of elements of same data type. Elements of an array are stored in contiguous memory locations in the storage.

    Syntax

    data_type array_name[array_size];

    Example

    #include <iostream>usingnamespace std;intmain(){int arr[5]={1,2,3,2,1};//define an integer array of size 5for(auto it:arr)
          cout<<it<<" ";//print the elements of arrayreturn0;}
    Output
    1 2 3 2 1 
    

    3. Pointer

    pointer is a reference to an element defined previously. The value of the pointer returns the address location of the element which is associated with it.

    Syntax

    data_type * pointer_name=& variable_name;

    Example

    #include <iostream>usingnamespace std;intmain(){int a=20;//declare variable aint*p=&a;//assign pointer to a
       cout<<"Address of variable a: "<<p<<endl;
       cout<<"Value of variable a: "<<*p<<endl;return0;}
    Output
    Address of variable a: 0x7ffc49a8637c
    Value of variable a: 20
    

    4. Reference

    reference variable is used to create a copy of a variable with the same reference. Hence, changes made to the reference variable also reflect on the original variable.

    Syntax

    data_type & reference_name= variable_name;

    Example

    #include <iostream>usingnamespace std;intmain(){int c=11;int& refer=c;
    
       cout<<"Initially value of integer is: "<<c<<endl;
    
       refer=121;
       cout<<"After changing value using refer variable :"<<c<<endl;return0;}
    Output
    Initially value of integer is: 11
    After changing value using refer variable :121
    

    User-Defined Data Types

    Data types which are defined by the user intuitively without using any pre-defined data types are known as User-Defined Data Types. These data types can be further categorized into five types, namely −

    1. Class

    class is a defined in Object Oriented Programming as a custom data type which is used to construct an object. It is the framework of an object, and it can include constructors, methods and OOP concepts like Polymorphism, Inheritance, etc.

    Syntax

    classClass_name{<classbody>class_name(parameters){<constructor body>}
    
       return_type method_name(paremeters){<method body>}}

    Example

    #include <iostream>usingnamespace std;classTP{public:
          string tp;voidprint(){
             cout<<tp<<endl;}};intmain(){
       TP object;
       object.tp="I Love Tutorialspoint !!!";
       object.print();return0;}
    Output
    I Love Tutorialspoint !!!
    

    2. Structure (struct)

    In structure data type, the user can introduce multiple primitive data types inside the struct body.

    Syntax

    structstruct_name{
       data_type1 var_name1;
       data_type2 var_name2;}

    Example

    #include <iostream>usingnamespace std;structTP{
       string tp;int grade;};intmain(){
       TP object;
       object.tp="I Love Tutorialspoint !!!";
       object.grade=10;
    
       cout<<object.tp<<endl;
       cout<<"How much would you rate it?"<<" : "<< object.grade;return0;}
    Output
    I Love Tutorialspoint !!!
    How much would you rate it? : 10
    

    3. Union

    Union is similar to a structure. In this, the memory location of all variables is same, and all variables share the same reference. Hence, a change in one value leads to all other values getting changed.

    Syntax

    union union_name{
       data_type var_name1;
       data_type var_name2;};

    Example

    #include <iostream>usingnamespace std;union TP{int tp1,tp2;};intmain(){union TP t;
       t.tp1=2;
       cout<<"Value of tp1 initially: "<<t.tp1<<endl;
    
       t.tp2=4;
       cout<<"When we change tp2, value of tp1 is : "<<t.tp1<<endl;return0;}
    Output
    Value of tp1 initially: 2
    When we change tp2, value of tp1 is : 4
    

    4. Enumeration (Enum)

    Enumeration or simply enum is a user-defined data type that is used to give name to integer constants in a program. This increases the user-readability of a program.

    Syntax

    enumenum_name{
       var_name1 , var_name2,}

    Example

    #include <iostream>usingnamespace std;enumTP{ C, Java, Python, Ruby, Kotlin, Javascript, TypeScript, Others};intmain(){enumTP course;
       cout<<"Which course do you love the most?"<<endl;
    
       course=Kotlin;
       cout<<"I love the "<<course+1<<"th course !!!";return0;}

    Output

    Which course do you love the most?
    I love the 5th course !!!
    

    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 −

    typedefint 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.

    Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is −

    enumenum-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”.

    enumcolor{ red, green, blue } c;
    c = blue;

    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.

    enumcolor{ 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++ Identifiers

    C++ identifiers are unique names assigned to identify variablesfunctionsclassesarrays, and other user-defined items in a program.

    The examples of identifier in C++ are −

    int number =10;
    string name ="John";

    Here, number and name are identifiers for an integer and a string variable respectively.

    Rules for Identifiers

    • It must begin with a letter (uppercase “A-Z” or lowercase “a-z”) or an underscore (_) but cannot start with a digit.
    • After the first character, subsequent characters can be letters, digits (0-9), or underscores.
    • Identifiers are case-sensitive (myVar and myvar are different).
    • It cannot be a keyword (reserved word in C++), for example, int, bool, return, and while, etc.
    • It must be unique within their namespace.
    • Use meaningful names that reflect the purpose of the identifier (e.g, totalCount, calculateArea).
    • In common practices, generally use camelCase or snake_case for readability.
    • There is generally no strict limit on the length, but avoid long names as they make code harder to read and understand.

    Types of Identifiers

    Here are examples of identifiers in various cases −

    1. Variable Identifiers

    Variable identifiers are names given to variables in programming languages, which are used to identify reference data stored in those variables.

    Here are a few examples of valid identifiers −

    int age;// 'age' is an identifier for an integer variabledouble salary;// 'salary' is an identifier for a double variablechar initial_alpha;// 'initial_alpha' is an identifier for a character variable

    2. Constant Identifiers

    Constant identifiers are names assigned to constants in programming, which represent fixed values that cannot be changed during the execution of a program.

    Here is a simple example of a valid constant identifier −

    constint MAX_SIZE =100;// 'MAX_SIZE' is an identifier for a constant

    3. Function Identifiers

    Function identifiers are names assigned to functions in programming, which allow developers to define and call reusable blocks of code.

    Some of the valid function identifiers are as follows −

    voidcalculateSum(){// 'calculateSum' is an identifier for a function// function implementation}intgetValue(){// 'getValue' is another function identifierreturn42;}

    4. Class Identifiers

    Class identifiers are names assigned to classes in object-oriented programming which is used to define new data types that encapsulate attributes and behaviors associated with specific entities.

    Here is a simple example of a valid class identifier −

    classPerson{// 'Person' is an identifier for a classpublic:int age;
          string name;};

    Example of Invalid Identifiers

    Here are a few examples of invalid identifiers −

    • 2ndValue (as it starts with a digit)
    • first-name (it contains a hyphen)
    • @username (begins with a special character)
    • my variable (contains a space)
    • float (uses a reserved keyword)
  • C++ Keywords

    In C++, keywords are reserved words that have special meanings to the compiler. They cannot be used for any other purpose or as identifiers, such as variables or function names. It’s a predefined words that are part of the C++ syntax. They help define the structure and behavior of the code.

    Basic Data Type keywords

    These keywords define basic data types −

    • int − integer data type.
    • char − character data type.
    • float − single-precision floating-point data type.
    • double − double-precision floating-point data type.
    • void − indicates no value or type; commonly used for functions that do not return a value.
    • Bool − boolean data type (true or false).
    • wchar_t − Represents wide character type mainly useful for internationalization.

    Control Flow Keywords

    Control flow keywords are special reserved words in programming that are used for implementing decision-making and repetitive tasks in programming.

    • Conditional Statements − if, else, switch, case, default
    • Looping Constructs − for, while, do
    • Control Statements − break, continue, return, goto

    Storage Class Keywords

    These keywords specify the storage duration and linkage of variables −

    • auto − The compiler automatically deduces the variable’s type (in C++11 and later).
    • Register − It suggests that the variable should be stored in a CPU register for faster access.
    • Static − It indicates that the variable retains its value even after the scope in which it was defined ends.
    • extern − It declares a variable that is defined in another translation unit.
    • Mutable − It allows a member of a class to be modified even if the object is constant.

    Modifiers

    These keywords are used in modifying the properties of data types −

    • const − It indicates that a variable’s value cannot be changed after initialization.
    • volatile − It indicates that a variable’s value may change unexpectedly, preventing certain compiler optimizations.
    • signed − It indicates that a data type can hold both positive and negative values.
    • unsigned − It indicates that a data type can only hold non-negative values.
    • short − It indicates a shorter version of the integer type.
    • long − It indicates a longer version of the integer type.

    Function Keywords

    These keywords define specific behavior for functions

    • inline − Suggests to the compiler to attempt to expand the function inline, reducing the overhead of a function call.
    • virtual − Indicates that a function can be overridden in derived classes.
    • explicit − Prevents implicit conversions for constructors or conversion operators.

    Class and Object Keywords

    These keywords are fundamental concepts in object-oriented programming (OOP) that enable developers to define and manipulate user-defined data types.

    • Class Definitions − class, struct, union, enum
    • Namespace Management − namespace, this
    • Memory Management − new, delete

    Access Specifiers

    Access specifiers are keywords in object-oriented programming that define the accessibility or visibility of class members (attributes and methods) to other parts of a program.

    • public
    • protected
    • private

    Exception Handling Keywords

    These keywords are used for handling exceptions

    • try − It defines a block of code to be tested for exceptions.
    • catch − It defines a block of code that handles exceptions thrown by a corresponding try.
    • throw − Used to signal the occurrence of an exception.

    Operator Keywords

    Operator keywords are keywords that allow you to define or change how operators (like +, -, *, etc.) work with custom data types, such as classes.

    • sizeof
    • typeid
    • alignof
    • alignas

    Namespace Keywords

    These keywords manage the scope of identifiers

    • namespace − Defines a scope that can contain identifiers to avoid name collisions.
    • using − Allows the use of names from a namespace without qualification.

    Type Casting Keywords

    These keywords are used for explicit type conversions

    • static_cast − It performs a compile-time type check and conversion.
    • dynamic_cast − Safely converts pointers or references within an inheritance hierarchy (requires RTTI).
    • const_cast − It adds or removes const or volatile qualifiers.
    • reinterpret_cast − It converts any pointer type to any other pointer type with no safety checks.

    Miscellaneous Keywords

    Some other keywords provided by the C++ library, that serve various purposes beyond the core functionalities of data types, control flow, or object-oriented programming.

    • using, typedef
    • Type Traits − decltype, static_assert
    • Casting Operators − static_cast, dynamic_cast, const_cast, reinterpret_cast

    Keywords Vs. Identifiers

    Keywords are predefined and reserved by the programming language, it has specific functions and meanings in the language while identifiers are user-defined names for program elements, They are created to represent variables, functions, and other entities in the code.

    Example

    KeywordsIdentifiers
    int, float, while, public, private, class, return, etc.myVariable, calculateSum, Person, _tempValue, etc.