Data types in C++ specify the types of data variables that may be stored, as well as how much memory they can hold and what operations are allowed. Three general categories can be used to classify C++ data types:
- Fundamental
- Derived
- User-defined
1. Fundamental (Built-in) Data Types
These data types serve as the basis for data representation and are predefined by the C++ language. They establish the types of data a variable can hold, how much memory it can hold, and what activities it may be used for. Among these, integer types are frequently used for indexing, general data storage, and numerical computations. These are fundamental types:
- Integer Types
- Floating-Point Types
- Character Type
- Boolean Type
- Void Type
a. Integer Types (int):
Integer data type in C++ is commonly utilized for storing whole numbers without any decimal points, making it a popular choice for values that do not require fractional accuracy.
i. Integer with sign: Typically, it requires 4 bytes of storage to hold integers with both positive and negative values. In a 32-bit environment, it can accommodate numbers ranging from -2,147,483,648 to 2,147,483,647.
Example:
signed int a = -10;
ii. Unsigned integer: This data type exclusively holds non-negative whole numbers (starting from 0) within a 4-byte storage capacity. The range of values it can accommodate spans from 0 to 4,294,967,295, which is double the range of a signed integer that covers -2,147,483,648 to 2,147,483,647.
Example:
unsigned int x = 18;
iii. Small int: A compact integer type typically occupying two bytes of memory. Although it comes with a restricted range (-32,768 to 32,767 for signed short), it proves beneficial in memory-constrained scenarios.
Example:
short int a = 1000;
iv. Extended integer: Typically occupying either 4 or 8 bytes, this category of integer is designed to hold larger numerical values compared to a standard integer. Its scope is dictated by the system's architecture, and on a 32-bit system, it is akin to an integer in terms of capacity.
Example:
long int a = 1000000;
C++ Integer Types Example:
Let's consider a scenario to demonstrate the Integer data type in C++.
Example:
#include <iostream>
int main()
{
int a = 13;
unsigned int b = 28;
short int c = 32747;
long int d= 1000000;
std::cout << "The value of a is: " << a << std::endl;
std::cout << "The value of b is: " << b << std::endl;
std::cout << "The value of c is: " << c << std::endl;
std::cout << "The value of d is: " << d << std::endl;
return 0;
}
Output:
The value of a is: 13
The value of b is: 28
The value of c is: 32747
The value of d is: 1000000
Explanation:
This C++ script defines four integer variables: a (standard int), b (unsigned int for values that are non-negative), c (short int with a limited range), and d (long int for handling larger numbers. By employing std::cout, it displays these variables after assigning them specific values. Consequently, the output exhibits the assigned values for each variable.
b. Floating-Point Types:
When it comes to storing real numbers, such as fractions and decimals, C++ offers three primary floating-point data types. These data types vary in precision and memory consumption, catering to a range of numerical calculations.
i. float (single precision): Float (Single Precision) requires 4 bytes of memory, offering approximately 6-7 decimal digits accuracy, suitable for standard calculations not requiring high precision.
Example:
float e = 49.4f;
ii. double (Double Precision): In the realm of floating-point calculations, the standard choice is Double (Double Precision), consuming 8 bytes and delivering a precision of 15-16 decimal digits.
Example:
double i = 4.478390278462748;
iii. long double (Extended Precision): In scenarios requiring precise scientific computations, long double (Extended Precision) is employed. It occupies over 10 bytes of memory and offers a range of 19 to 21 decimal places for accuracy.
Example:
long double h = 6.987271836478124679L;
C++ Floating-Point Types Example:
Let's consider a scenario to demonstrate the floating-point data type in C++.
Example:
#include <iostream>
#include <iomanip>
int main()
{
float f_1 = 3.1415926535f;
double d_2 = 3.1415926535;
long double ld_3 = 3.141592653589793238L;
std::cout << std::fixed << std::setprecision(10);
std::cout << "The float value is: " << f_1 << std::endl;
std::cout << "The double value is: " << d_2 << std::endl;
std::cout << "The long double value is: " << ld_3 << std::endl;
return 0;
}
Output:
The float value is: 3.1415927410
The double value is: 3.1415926535
The long double value is: 3.1415926536
Explanation:
The distinctions in precision among the float, double, and long double data types are illustrated in this C++ code snippet. By employing the std::fixed and std::setprecision(10) manipulators, numeric values are exhibited with a precision of ten decimal places. The script leverages the mathematical constant π (pi) to initialize three variables (f1, d2, and ld_3) at varying levels of accuracy. This showcases the superior decimal precision retention of long double compared to float and double, as each number is output to the console.
c. Character Type (char):
In C++, a solitary character can be held in a solitary byte (8 bits) of storage by making use of the char data type. The ASCII (American Standard Code for Information Interchange) encoding is predominantly employed for character representation. Nevertheless, wchart, char16t, and char32_t are employed to offer UTF-16 and UTF-32 encoding for Unicode characters. These data types are capable of representing any character from the ASCII or Unicode set, encompassing digits, alphabets, special characters, and additional symbols.
Example:
char letter = 'A';
C++ Character Type Example:
Let's consider a scenario to demonstrate the Character data type in C++.
Example:
#include <iostream>
int main()
{
char ch = 'C';
char d = '7';
char s = '$';
std::cout << "Character: " << ch << std::endl;
std::cout << "Digit: " << d << std::endl;
std::cout << "Symbol: " << s << std::endl;
// Displaying ASCII values
std::cout << "The ASCII of " << ch << " is " << int(ch) << std::endl;
std::cout << "The ASCII of " << d << " is " << int(d) << std::endl;
std::cout << "The ASCII of " << s << " is " << int(s) << std::endl;
return 0;
}
Output:
Character: C
Digit: 7
Symbol: $
The ASCII of C is 67
The ASCII of 7 is 55
The ASCII of $ is 36
Explanation:
This C++ code example showcases the utilization of the char data type by assigning a distinct character to variables letter, digit, and symbol. Subsequently, these characters are outputted using std::cout, and int is employed to transform them into integers to exhibit the correlated ASCII values. ASCII values are numerical representations assigned to characters in the ASCII table. For instance, characters C, 7, and $ correspond to ASCII values 67, 55, and 36, respectively. This demonstration illustrates the significance of ASCII conversions in various text manipulation techniques as characters are stored internally as numeric values.
d. Boolean Type (bool):
In C++, the Boolean data type (bool) is responsible for storing logical values representing true and false. It plays a crucial role in control flow, conditional statements, and decision-making processes, allowing for the efficient assessment of logical expressions and conditions.
Example:
bool b = true;
bool f = false;
C++ Boolean Type Example:
Let's consider an example to demonstrate the Boolean data type in C++.
Example:
#include <iostream>
using namespace std;
int main()
{
bool isLoggedIn = true;
bool hasAccess = false;
cout << "User logged in: " << isLoggedIn << endl;
cout << "User has access: " << hasAccess << endl;
if (isLoggedIn && hasAccess)
{
cout << "Access granted!" << endl;
}
else
{
cout << "Access denied!" << endl;
}
return 0;
}
Output:
User logged in: 1
User has access: 0
Access denied!
Explanation:
This C++ code example illustrates the implementation of conditional expressions and boolean variables. Initially, the program sets the variables isLoggedIn to true and hasAccess to false, followed by displaying their states through the cout function. Within the if statement, the logical AND (&&) operator is applied to assess if both conditions are met; if affirmative, the message "Access granted!" is shown; otherwise, "Access denied!" is displayed. In this scenario, the output will be "Access denied!" since the value of hasAccess is false.
e. Void Type (void):
The void keyword in C++ signifies the absence of a specific data type. It is commonly employed for defining generic pointers, indicating that a function has no return value, and for specifying functions with unspecified arguments. Unlike other data types, void does not hold any value and cannot be directly utilized for variable declarations.
C++ Void Type Example:
Let's consider an example to demonstrate the Void data type in C++.
Example:
#include <iostream>
using namespace std;
// Function with void return type
void greet()
{
cout << "Hello World!" << endl;
}
int main()
{
greet(); // Function call
return 0;
}
Output:
Hello World!
Explanation:
It produces no output as the greet function in the provided C++ code has a void return type. The message "Hello World!" is outputted to the screen through cout inside the function. The main function triggers the greet function, leading to the execution of the code and the display of the greeting. Successful execution is indicated by the printing of "Hello World!" and a return value of 0.
2. Derived Data Types
Constructed data types are created by combining fundamental types to enhance functionality and enable sophisticated data processing and storage capabilities. These features support organized programming methodologies for effective data management and optimized memory usage.
Types of Derived Data Types:
Several types of derived data types are as follows:
- Arrays
- Pointers
- References
a. Arrays:
A set-size grouping of items of identical type arranged in contiguous memory locations is known as an array. Arrays enhance data handling efficiency by consolidating numerous values within a single variable identifier.
i. One-Dimensional Array:
A sequential grouping of elements stored in memory is referred to as a one-dimensional array. One-dimensional arrays are beneficial for holding series of data as they are defined with a single index.
Example:
int a[3] = {15, 32, 53};
ii. Multi-Dimensional Array (2D, 3D, etc.):
A multi-dimensional array is an array composed of arrays, typically employed to depict matrices or grids. Additional dimensions expand upon the rows and columns present in a 2D array.
Example:
int a[3][3] = {{13, 21, 56}, {34, 25, 76}, {17, 48,2 9}};
iii. Dynamic arrays:
Dynamic array allocation during runtime is achieved using pointers and the new keywords. It is essential to manually deallocate them, although they offer versatility in memory utilization.
Example:
int* a = new int[5]; delete[] a;
C++ Arrays Example:
Let's consider an example to demonstrate the usage of Arrays in C++.
Example:
#include <iostream>
using namespace std;
int main()
{
// 1. One-Dimensional Array
int a[5] = {10, 20, 30, 40, 50};
cout << "One-Dimensional Array:" << endl;
for (int q = 0; q < 5; q++)
{
cout << a[q] << " ";
}
cout << "\n\n";
// 2. Two-Dimensional Array (2x3 Matrix)
int b[2][3] = {
{21, 42, 35},
{54, 87, 64}
};
cout << "Two-Dimensional Array (Matrix):" << endl;
for (int q = 0; q < 2; q++)
{
for (int k = 0; k < 3; k++)
{
cout << b[q][k] << " ";
}
cout << endl;
}
cout << "\n";
// 3. Dynamic Array (Size taken from the user)
int size;
cout << "Enter the size of the dynamic array: ";
cin >> size;
// Allocating memory dynamically
int* c = new int[size];
// Initializing dynamic array
for (int q = 0; q < size; q++)
{
c[q] = (q + 1) * 10;
}
cout << "Dynamic Array:" << endl;
for (int q = 0; q < size; q++)
{
cout << c[q] << " ";
}
cout << "\n";
// Freeing dynamically allocated memory
delete[] c;
return 0;
}
Output:
One-Dimensional Array:
10 20 30 40 50
Two-Dimensional Array (Matrix):
21 42 35
54 87 64
Enter the size of the dynamic array: 3
Dynamic Array:
10 20 30
Explanation:
The C++ examples illustrate different types of arrays such as one-dimensional, two-dimensional, and dynamic arrays. An array of five numbers is first initialized using a loop and then its elements are printed. Following that, a 2x3 matrix is created and the values are shown in matrix format by traversing through its rows and columns.
Subsequently, the program prompts the user to specify the size of a dynamic array, allocates memory using the 'new' keyword, sets initial values in the array as multiples of 10, and displays the array contents. To ensure proper memory management and prevent memory leaks, the program deallocates the memory using 'delete' at the conclusion. This program showcases concepts such as dynamic memory allocation, array manipulation, and iteration methods in C++.
b. Pointers:
A pointer serves as a variable that stores the memory address of another variable, enhancing memory operations efficiency by referencing a memory location instead of a specific value. Pointers are crucial for various aspects such as data structures, dynamic memory allocation, function pointers, and optimized parameter passing within functions.
C++ Pointers Example:
Let's consider an example to demonstrate the concept of Pointers in C++.
Example:
#include <iostream>
using namespace std;
int main()
{
int a = 100;
int* ptr = &a;
cout << "The value of is: " << a << endl;
cout << "The address of is: " << &a << endl;
cout << "The pointer ptr stores address: " << ptr << endl;
cout << "The value pointed by ptr: " << *ptr << endl;
return 0;
}
Output:
The value of a is: 100
The address is: 0x7ffd7a1800c4
The pointer ptr stores address: 0x7ffd7a1800c4
The value pointed by ptr: 100
Explanation:
This C++ code example demonstrates how memory addresses are stored and accessed using pointers. An integer variable named "a" is declared with a value of 100, and a pointer named ptr is assigned the address of "a". By dereferencing the pointer (*ptr), the program displays the value of "a", its memory address, the address stored in ptr, and the value located at that address. This showcases the direct manipulation of memory through pointer usage.
c. References:
A reference in C++ acts as a substitute name for a different variable. Rather than establishing a fresh memory space, a reference alters the identifier of an already existing variable. This signifies that any modifications made through the reference directly affect the original variable.
C++ References Example:
Let's consider an example to demonstrate the concept of References in C++.
Example:
#include <iostream>
using namespace std;
int main()
{
int num = 5;
int& ref = num;
cout << "Original value: " << num << endl;
ref = 10; // Changing ref also changes num
cout << "Modified value: " << num << endl;
return 0;
}
Output:
Original value: 5
Modified value: 10
Explanation:
This C++ code showcases the concept of references. Along with establishing a reference named ref that acts as a synonym for num, it declares an integer variable num. The initial output of num reveals the value 5. Subsequently, the ultimate result exhibits 10 after modifying ref, consequently updating the value of num. This showcases the capability of references in providing an alternative identifier for a variable, enabling efficient modifications without generating redundant copies.
3. User-Defined Data Types:
By leveraging user-defined data types, developers can create various kinds in C++ apart from the predefined basic types. These custom types facilitate modular programming, data structuring, and code comprehension. They enhance the manageability of intricate programs by enabling the consolidation of related variables and functionalities under a unified identifier.
Types of User-Defined Data Types:
Several types of user-defined data types in C++ are as follows:
- Struct
- Class
- Union
- Enumeration (enum)
- Typedef and Using
1. Struct:
A custom-defined data type referred to as a structure (struct) enables the grouping of multiple variables of different data types under a single identifier. This simplifies the organization of related data and enhances the readability and maintainability of the code. Objects with multiple attributes, such as a student, employee, or car, are commonly modeled using structures.
C++ Struct Example:
Let's consider an example to demonstrate the use of the Struct in C++.
Example:
#include <iostream>
using namespace std;
// Defining a Structure for a Student
struct Student
{
int id;
char name[50];
float grade;
};
void displayStudent(const Student& s)
{
cout << "The ID is: " << s.id << endl;
cout << "The Name is: " << s.name << endl;
cout << "The Grade is: " << s.grade << endl;
}
int main()
{
Student s1 = {18, "John", 86.5};
displayStudent(s1);
return 0;
}
Output:
The ID is: 18
The Name is: John
The Grade is: 86.5
Explanation:
The provided C++ code defines a structure named Student, which includes three properties: grade (a decimal number), name (an array of characters), and id (a whole number). By employing cout, the displayStudent method exhibits the information of a Student structure received as a constant reference. Within the main function, a structure instance s1 is declared and set with values {18, "John", 86.5}. Subsequently, the program invokes displayStudent(s1) to exhibit the particulars of John on the screen.
b. Class
A class plays a vital role in object-oriented programming (OOP) within C++. It acts as a template for creating objects and serves as a custom data type. Within a class, data members (variables) and member functions (methods) define the properties and behaviors of instantiated objects. This encapsulation guarantees program organization and recyclability by encouraging data abstraction and concealment.
C++ Class Example:
Let's consider an example to demonstrate the concept of a Class in C++.
Example:
#include <iostream>
using namespace std;
// Defining a class
class Bike
{
private:
string brand;
public:
Bike(string b)
{
brand = b;
}
void showBrand()
{
cout << "Bike brand: " << brand << endl;
}
};
int main()
{
Bike bike1("KTM");
Bike bike2("Royal Enfield");
bike1.showBrand();
bike2.showBrand();
return 0;
}
Output:
Bike brand: KTM
Bike brand: Royal Enfield
Explanation:
The Bike class is instantiated through a public constructor and contains a private attribute called brand. To maintain encapsulation, the showBrand method is responsible for revealing the brand name. This function is employed to exhibit the brands of the two instances (bike1 and bike2) generated within the main function.
c. Union:
Unions are custom data types that allow grouping multiple data types into a unified entity, similar to structures. Unlike structures, all members of a union occupy the same memory location. This means that modifying one member will replace any existing data, limiting a union to holding a single value at any given time.
C++ Union Example:
Let's consider an example to demonstrate the concept of Union in C++.
Example:
#include <iostream>
using namespace std;
// Defining a union
union Demo {
int int_Value;
float float_Value;
char char_Value;
};
int main()
{
Demo d;
d.int_Value = 48;
cout << "Integer Value: " << d.int_Value << endl;
d.float_Value = 3.14;
cout << "Float Value: " << d.float_Value << endl;
d.char_Value = 'A';
cout << "Character Value: " << d.char_Value << endl;
cout << "After modification, the Integer Value is: " << d.int_Value << endl;
return 0;
}
Output:
Integer Value: 48
Float Value: 3.14
Character Value: A
After modification, the Integer Value is: 1078523201
Explanation:
A union named Demo is declared within this C++ code, capable of storing either a char, float, or int, but limited to one value at a time. The main function illustrates how a union updates existing data when a new value is assigned by consecutively assigning diverse values to the union variable d. The result highlights that solely the most recently assigned value remains accurate, with prior values being altered due to the common memory space.
d. Enumeration (enum):
In C++, significant names for integral constants are commonly assigned through an enumeration (enum), which is a custom data type. Enumerations allow developers to define a series of named integer constants instead of relying on plain integers. This practice enhances the readability, organization, and sustainability of the program.
C++ Enumeration Example:
Let's consider a scenario to demonstrate the Enumeration (enum) concept in the C++ programming language.
Example:
#include <iostream>
using namespace std;
// Defining an enumeration
enum Colour {
RED,
GREEN,
BLUE
};
int main()
{
Colour favoriteColour;
favoriteColour = BLUE;
if (favoriteColour == BLUE)
{
cout << "Your favorite color is Blue!!" << endl;
}
return 0;
}
Output:
Your favorite color is Blue!!
Explanation:
This C++ code initializes three constants within the enum Colour: RED, GREEN, and BLUE. Within the main function, the variable favoriteColour of type Colour is declared and initialized with the value BLUE. An if statement is used to display "Your preferred color is Blue!!" if the favoriteColour is set to BLUE.
e. Typedef and Using:
In C++, Typedef and Using are employed to assign alternative names to existing data types, enhancing the clarity and versatility of the code. Instead of creating new data types, they serve as aliases, simplifying the process of adjusting and customizing code for various platforms.
C++ Typedef and Using Example:
Let's consider a scenario to demonstrate the Typedef and Using directives in C++.
Example:
#include <iostream>
using namespace std;
typedef unsigned int uint;
using ull = unsigned long long;
int main()
{
uint x = 10;
ull y = 10000000000;
cout << "x: " << x << "\n";
cout << "y: " << y << "\n";
return 0;
}
Output:
x: 10
y: 10000000000
Explanation:
This C++ code utilizes typedef to create aliases for data types: uint for unsigned int and ull for unsigned long long. Within the main function, variables x and y are declared as unsigned int and unsigned long long respectively, and values are assigned to them. The program concludes by using cout to display the values of x and y.
C++ Data Types MCQS
- In C++, which of the following is NOT a fundamental data type?
- double
- char
- string
- What is the size of the C++ bool data type?
- 2 bytes
- 1 byte
- 8 bytes
- 4 bytes
- What is the proper declaration for a floating-point variable in C++?
- float num = 10.5;
- char num = '10.5';
- double num = 10;
- int num = 10.5;
- In C++, which of the following declares about enum is TRUE?
- enum can store string values.
- enum members must be declared inside a class only.
- enum assigns integer values to its members by default.
- enum is used to store decimal values.
- When storing a large integer value that is above of the int range in C++, which data type is best suited?
- short
- long
- float
- long long