Concept Of Data Types

A data type in C++ specifies the type of data that a variable can hold, such as integers, floating-point numbers, characters, and more. When declaring variables, specifying a data type is essential to restrict the type of data they can store, ensuring type safety and preventing unintended operations. Additionally, each data type in C++ requires a specific amount of memory space for storage, with sizes varying depending on the type. By offering a diverse range of data types,

C++ allows programmers to select the most suitable type for their application, optimizing memory usage and ensuring accurate data representation. While storage representation and machine instructions may differ across hardware architectures, the C++ language ensures that code instructions remain consistent and portable across platforms.

Types of data types

  1. Primary or Built-in or Fundamental data type
  2. Derived data types
  3. User-defined data types
Data Types

Built-in Data Types

  • Character
  • Integer
  • Float
  • Double

Character

Character data type is used for storing characters. The keyword used for the character data type is char. Characters typically require 1 byte of memory space and range from -128 to 127. Characters in C++ are enclosed inside single quotes ' '.

For Example:-

#include<iostream>
using namespace std;
 
int main(){
   // initializing a variable
    char ch = 'e';
 
    // printing the  variable
    cout << "Character = " << ch << endl;
 
    return 0;
}

Output:-

Character = e

In the example above, we have declared a character type variable named ch. We then assigned the character e to it.

Note: In C and C++, a character should be inside single quotation marks. If we use, double quotation marks, it's a string.

ASCII Value

In C and C++, an integer (ASCII value) is stored in char variables rather than the character itself. For example, if we assign 'h' to a char variable, 104 is stored in the variable rather than the character itself. It's because the ASCII value of 'h' is 104.

Here is a table showing the ASCII values of characters A, Z, a, z and 5.

CharacterASCII Values
A65
Z90
a97
z122
553

Example 1: Get ASCII Value of a Character

#include <iostream>
using namespace std;
 
int main() {
    char ch = 'e';
 
    // Printing the corresponding ASCII of a character
    // Notice the use of int() to get an integer
    cout << "ASCII value = " << int(ch) << endl;
 
    return 0;
}

Output:-

ASCII value = 101

We can assign an ASCII value (from 0 to 127) to the char variable rather than the character itself.

Example 2: Print Character Using ASCII Value

#include <iostream>
using namespace std;
 
int main() {
 
    // assigning an integer value to char
    char ch = 101;
 
    // printing the variable
    cout << "Character = " << ch << endl;
 
    return 0;
}

Output:-

Character = e

Note: If we assign '5' (quotation marks) to a char variable, we are storing 53 (its ASCII value). However, if we assign 5 (without quotation marks) to a char variable, we are storing the ASCII value 5.

C++ Escape Sequences

Some characters have special meaning in C++, such as single quote ', double quote ", backslash \ and so on. We cannot use these characters directly in our program.

For example,

// This code shows an error
char character = ''';

So how can we use those special characters?

To solve this issue, C++ provides special codes known as escape sequences. Now with the help of escape sequences, we can write those special characters as they are.

For example,

// does not show error
char character = ' \' ';

Here, \' is an escape sequence that allows us to store a single quote in the variable.

The table below lists some escape sequences of C++.

Escape SequencesCharacters
\bBackspace
\nNewline
\tHorizontal Tab
  1. \b - Backspace character:
  • It is used to insert a backspace in a string or a character literal.

  • When encountered in a string or character literal, it moves the cursor back one position.

  • It is used to erase the character preceding the backspace and can be used to create effects like a progress bar or animated text.

  1. \n - Newline character:
  • It is used to insert a newline or line break in a string or a character literal.

  • When encountered in a string or character literal, it moves the cursor to the beginning of the next line.

  • It is used to separate lines of text and start writing on a new line.

  1. \t - Tab character:
  • It is used to insert a horizontal tab in a string or a character literal.

  • When encountered in a string or character literal, it moves the cursor to the next tab stop, which is typically at every eighth column.

  • It is commonly used for aligning text in a formatted manner.

Example: Using C++ Escape Sequences

#include <iostream>
using namespace std;
 
int main() {
    char character1 = 'A';
 
     // using escape sequence for horizontal tab
    char character2 = '\t';
 
    char character3 = '5';
 
     // using escape sequence for new line
    char character4 = '\n';
 
    char character5 = 'a';
 
    // printing the variables
    cout << character1;    // A
    cout << character2;    // horizontal tab
    cout << character3;    // 5
    cout << character4;    // new line
    cout << character5;    // a
 
    return 0;
}

Output:-

A       5
a

In the above program, we have used two escape sequences: the horizontal tab \t and the new line \n.

Integer

The keyword used for integer data types is int. It does not support any decimal or fractional number. Integers typically require 4 bytes of memory space and range from -2147483648 to 2147483647. Integer numbers can contain Positive as well as Negative numbers.

Int Data Type is further divided into 2 types -

Signed Int - Allows positive as well as negative numbers.
Unsigned Int - Allows only positive numbers.

For Example:-

#include<iostream>
using namespace std;
 
int main(){
   // initializing a variable
    int var = 7;
 
    // printing the  variable
    cout << "Variable is = " << var << endl;
 
    return 0;
}

Output:-

Variable is = 7

Float And Double

Floating Point data type is used for storing single-precision floating-point values (decimals and exponentials). The keyword used for the floating-point data type is float. Float variables typically require 4 bytes of memory space.

Double Floating Point data type is used for storing double-precision floating-point values (decimals and exponentials). The keyword used for the double floating-point data type is double. Double variables typically require 8 bytes of memory space.

Example: C++ float and double

#include <iostream>
using namespace std;
 
int main() {
    // Creating a double type variable
    double a = 3.912348239293;
 
    // Creating a float type variable
    float b = 3.912348239293;
 
    // Printing the two variables
    cout << "Double Type Number  = " << a << endl;
    cout << "Float Type Number  = " << b << endl;
 
    return 0;
}
Double Type Number  = 3.91235
Float Type Number = 3.91235

Note: The compiler used for this example (MinGW compiler) allowed for 6 digits. So, our variable values were rounded off and truncated to 6 digits by the compiler.

As mentioned above, these two data types are also used for exponentials. For example,

 double distance = 2E4 ;   // 2E4 is equal to 2*10^4

Boolean Data Type (bool)

  • The bool data type is used to represent Boolean values, which can have one of two states: true or false.
  • It is primarily used in conditional expressions and logical operations to control program flow.
  • In memory, a bool typically occupies one byte, but its value is either true (non-zero) or false (zero).

Void Data Type (void)

  • The void data type is used to indicate that a function does not return any value.
  • It is commonly used for functions that perform a task without returning a result, such as functions that print output or modify global variables.
  • Variables cannot be declared with void as their type, but it can be used as a pointer type (void*) to represent a pointer that can point to objects of any type.

Wide Character Data Type (wchar_t)

  • The wchar_t data type is used to represent wide characters, which are typically used to support internationalization and multilingual text processing.
  • It is capable of storing a wider range of characters than the char data type, allowing representation of characters from various languages and character sets.
  • The size of wchar_t is implementation-defined but is commonly 2 or 4 bytes.
  • Wide characters are often used with wide-character string literals (L"string") and wide-character input/output functions (wprintf, wscanf).

Derived Data Types

  1. Functions

  2. Array

  3. Pointers

    • A pointer is a variable that stores the memory address of another variable.
    • It is declared using the asterisk (*) symbol before the variable name.
    • Pointers can be initialized to point to another variable or dynamically allocated memory using the address-of operator (&) or the new keyword.
    • They are used for dynamic memory allocation, passing parameters by reference, and implementing data structures like linked lists and trees.
    • Pointers can be reassigned to point to different memory locations during runtime.
    • They require explicit memory management, including memory deallocation (delete operator) to avoid memory leaks.
    int x = 10;
    int *ptr;       // Pointer declaration
    ptr = &x;       // Pointer initialization
    int y = *ptr;   // Dereferencing pointer
  4. References

    • A reference is an alias or alternative name for an existing variable.
    • It is declared using the ampersand (&) symbol after the variable type.
    • References must be initialized when declared and cannot be changed to refer to another variable.
    • They provide a convenient and safe way to work with existing variables without the overhead of pointers.
    • References are often used as function parameters to pass arguments by reference, enabling functions to modify their arguments directly.
    int x = 10;
    int &ref = x;   // Reference declaration and initialization
    ref = 20;       // Modifying the referred variable

User Defined Data Types

  1. Class

  2. Structure

  3. Union

    • A union is a special data type that allows storing different data types in the same memory location.
    • All members of a union share the same memory space, and modifying one member will affect the value of other members.
    • Unions are useful when you need to store different types of data but only one type at a time.
    • The size of a union is determined by the size of its largest member.
    • Accessing different members of a union is done using the dot (.) operator.
    union MyUnion {
     int intValue;
     float floatValue;
     char charValue;
    };
     
    MyUnion u;
    u.intValue = 42;
    cout << u.intValue;  // Output: 42
    u.floatValue = 3.14f;
    cout << u.intValue;  // Output: depends on floating-point representation
  4. Enum

    • Enumerations (enums) are user-defined data types that consist of a set of named constants called enumerators.
    • Enums provide a way to associate symbolic names with integral values, making the code more readable and maintainable.
    • By default, the first enumerator has the value 0, and the value of each subsequent enumerator is incremented by 1.
    • Enumerators can also be assigned specific values explicitly.
    • Enums are often used to define a set of related constants or to create custom data types with a finite set of possible values.
    enum Color { RED, GREEN, BLUE };
     
    Color c = GREEN;
    if (c == GREEN) {
        cout << "The color is green.";
    }
  5. Typedef

    • The typedef keyword is used to create aliases or alternative names for existing data types.
    • It allows programmers to define custom names for complex data types, making the code more readable and easier to maintain.
    • Typedefs are particularly useful when working with complex data structures, function pointers, or to improve code portability.
    • Once a typedef is defined, the new name can be used in place of the original data type throughout the code.
    typedef int IntArray[5];  // Typedef for an array of integers
     
    IntArray numbers = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; ++i) {
        cout << numbers[i] << " ";
    }
     
    // Output: 1 2 3 4 5
How's article quality?

Page Contents