Ever wondered why your C++ program crashes or gives unexpected results? Often, it’s due to incorrect data types. Understanding them is crucial for writing efficient code.
Data types are relevant as they establish the type of data a variable can contain.
They are important because they help in the decision-making process and facilitate the correct amount of memory to be provided, as well as the operations that can be done on the data.
One of the problems that can result here is that using the wrong data type can cause strange bugs, inefficient memory usage and so on. For instance, when attempting to store a large decimal value in an integer, we only retain its integer value and lose on the decimal component.
Data types in C++ can be classified into three parts:
Primitive/Built-in Datatypes
Derived Datatypes
Abstract/User-defined Datatypes
This article will classify the data types in C++ and help you understand how they work.
These data types are either predefined or built-in, and the user can declare variables using them directly.
Different types of primitive data types in C++ are:
Integer Data Types in C++
Integers are for whole numbers. We use them in daily life, like counting apples or marking ages. In C++, we have different integer types to suit various needs.
Types of Integer Data Types:
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: "; cin >> age;
cout << "You are " << age << " years old." << endl;
return 0;
}
Character Data Types in C++
Characters store single letters or symbols. This includes letters in your name or symbols like @ and #.
Example:
#include <iostream>
using namespace std;
int main() {
char initial;
cout << "Enter the first letter of your name: "; cin >> initial;
cout << "Your initial is " << initial << "." << endl;
return 0;
}
Boolean Data Types in C++
Booleans store true or false values. We use them to make decisions in code. It is generally used in loops and conditional statements.
Example:
#include <iostream>
using namespace std;
int main() {
bool isCodingFun;
cout << "Is coding fun? (1 for yes, 0 for no): "; cin >> isCodingFun;
if (isCodingFun)
cout << "Glad to hear you enjoy coding!" << endl;
else
cout << "Maybe it will grow on you." << endl;
return 0;
}
Floating Point and Double Floating Point Data Types in C++
Floating-point numbers store decimal values. They are useful for precise calculations like measuring weight or distance.
Types of Floating Points:
Example:
#include <iostream>
using namespace std;
int main() {
float weight;
cout << "Enter your weight in kg: "; cin >> weight;
cout << "Your weight is " << weight << " kg." << endl;
return 0;
}
Void Data Type: Purpose and Use Cases
The void type means no value. We use it for functions that don’t return a value. It represents a valueless entity.
Wide Character Data Types for Extended Character Sets
The wide-character and char data types are comparable to one another. It is used to represent characters that require more memory than can be represented by a single character.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Detailed Discussion on Derived Data Types
Handling complex data in C++ can be tricky. Derived data types are here to help. They offer more control and flexibility for advanced programming.
These types help us manage various data efficiently and write advanced programs. We can classify derived data types into four sections:
Functions: Definition and Examples
Functions are blocks of code designed to perform specific tasks. They make our code reusable and organised.
It is created to save the user from having to write the same code for the same input many times. We can call functions whenever needed, reducing code duplication.
Main() is a default function included in all C++ applications. In addition, the function includes a return type that indicates the kind of data the function will return at the end of its execution.
Example:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int num1, num2;
cout << "Enter two numbers: "; cin >> num1 >> num2;
cout << "Sum: " << add(num1, num2) << endl;
return 0;
}
Arrays: Usage and Examples
Arrays store multiple elements of the same type in a single variable. They are useful for handling lists of values.
Arrays allow us to store a lot of data in a single variable name and sequential order. Each element in an array can be accessed using its index.
Example:
#include <iostream>
using namespace std;
int main() {
int numbers[5];
cout << "Enter 5 numbers: ";
for(int i = 0; i < 5; i++) { cin >> numbers[i];
}
cout << "You entered: ";
for(int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
Pointers: Definition and Practical Applications
Pointers store the memory address of a variable. They are powerful tools for dynamic memory management. They are used for dynamic memory allocation and accessing array elements.
Example:
#include <iostream>
using namespace std;
int main() {
int value = 10;
int *ptr = &value;
cout << "Value: " << value << endl;
cout << "Pointer points to value: " << *ptr << endl;
return 0;
}
References: Use Cases and Examples
A variable that has been declared as a reference becomes a different name for an already-existing variable. They are simpler and safer than pointers.
A variable can be defined as a reference by adding ‘&’ to its declaration. They provide a way to access variables without using pointers.
Example:
#include <iostream>
using namespace std;
int main() {
int number = 100;
int &ref = number;
cout << "Number: " << number << endl;
cout << "Reference to number: " << ref << endl;
return 0;
}
Exploring User-Defined Data Types in C++
User-defined data types let us create structures tailored to our needs. They offer more flexibility and control.
C++ provides the following five user-defined datatypes:
Classes: Blueprint for Complex Data Types
Classes combine data and functions into a single unit. They are the foundation of object-oriented programming.
Example:
#include <iostream>
using namespace std;
class Car {
public:
string brand;
string model;
int year;
void displayInfo() {
cout << brand << " " << model << " (" << year << ")" << endl;
}
};
int main() {
Car car1;
cout << "Enter car brand, model, and year: "; cin >> car1.brand >> car1.model >> car1.year;
car1.displayInfo();
return 0;
}
Structures: Combining Different Data Types
Structures are user-defined data types that group different data types. They help in organizing complex data.
Unions allow different data types to share the same memory location. They help save memory by using the same location for multiple variables.
Example:
#include <iostream>
using namespace std;
union Data {
int intValue;
float floatValue;
char charValue;
};
int main() {
Data data;
data.intValue = 5;
cout << "Int value: " << data.intValue << endl;
data.floatValue = 3.14;
cout << "Float value: " << data.floatValue << endl;
data.charValue = 'A';
cout << "Char value: " << data.charValue << endl;
return 0;
}
Enumerations: Defining Named Constants
Enumerations allow us to define a set of named integer constants. They improve code readability and maintainability.
Example:
#include <iostream>
using namespace std;
enum Day { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
int main() {
Day today = Wednesday;
cout << "Today is: " << today << endl;
return 0;
}
Typedef: Creating New Type Names
Typedef allows us to create new names for existing data types. It improves code readability and makes it easier to manage data types.
Typedef can help with the self-documentation of code by allowing descriptive names for common data types.
Example:
#include <iostream>
using namespace std;
typedef long int LongInt;
int main() {
LongInt largeNumber = 123456789;
cout << "Large number: " << largeNumber << endl;
return 0;
}
Modifiers for Data Types in C++
Modifiers change the size or type of data types. They help us optimize memory usage and control data ranges.
Data type modifiers available in C++ are:
Signed and Unsigned Modifiers
Signed and unsigned modifiers affect the range of data types.
Signed types can represent both positive and negative values.
Unsigned types can represent only positive values.
Example:
#include <iostream>
using namespace std;
int main() {
unsigned int positiveNumber = 50;
signed int negativeNumber = -50;
cout << "Unsigned: " << positiveNumber << endl;
cout << "Signed: " << negativeNumber << endl;
return 0;
}
Short and Long Modifiers
Short and long modifiers adjust the size of integer data types.
Short types have a smaller range and use less memory.
Long types have a larger range and use more memory.
Example:
#include <iostream>
using namespace std;
int main() {
short int shortNumber = 32767;
long int longNumber = 2147483647;
cout << "Short: " << shortNumber << endl;
cout << "Long: " << longNumber << endl;
return 0;
}
Memory Space and Range of Different Data Types
Data Type
Size (in bytes)
Range
short int
2
-32,768 to 32,767
unsigned short int
2
0 to 65,535
unsigned int
4
0 to 4,294,967,295
int
4
-2,147,483,648 to 2,147,483,647
long int
4
-2,147,483,648 to 2,147,483,647
unsigned long int
4
0 to 4,294,967,295
long long int
8
-(2^63) to (2^63)-1
unsigned long long int
8
0 to 18,446,744,073,709,551,615
signed char
1
-128 to 127
unsigned char
1
0 to 255
float
4
-3.4×10^38 to 3.4×10^38
double
8
-1.7×10^308 to1.7×10^308
long double
12
-1.1×10^4932 to1.1×10^4932
wchar_t
2 or 4
1 wide character
bool
1
True or false
Practical Examples of Data Types in C++
Example 1: Using Different Data Types Together
In this example, we will use int, float, char, and bool.
#include <iostream>
using namespace std;
int main() {
int age;
float height;
char initial;
bool isStudent;
cout << "Enter your age: "; cin >> age;
cout << "Enter your height in meters: "; cin >> height;
cout << "Enter the first letter of your name: "; cin >> initial;
cout << "Are you a student? (1 for yes, 0 for no): "; cin >> isStudent;
cout << "You are " << age << " years old, " << height << " meters tall, ";
cout << "your name starts with " << initial << ", and it is ";
cout << (isStudent ? "true" : "false") << " that you are a student." << endl;
return 0;
}
Output:
Example 2: Working with Arrays
This code takes five test scores and prints them out.
#include <iostream>
using namespace std;
int main() {
int scores[5];
cout << "Enter 5 test scores: ";
for(int i = 0; i < 5; i++) { cin >> scores[i];
}
cout << "You entered: ";
for(int i = 0; i < 5; i++) {
cout << scores[i] << " ";
}
cout << endl;
return 0;
}
Output:
Example 3: Using Structures
This code collects and displays details of a book using a structure.
This code dynamically allocates an array and frees the memory after use.
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the number of elements: "; cin >> n;
int* arr = new int[n];
cout << "Enter " << n << " elements: ";
for(int i = 0; i < n; i++) { cin >> arr[i];
}
cout << "You entered: ";
for(int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
delete[] arr;
return 0;
}
Output:
Conclusion
In this article, we explored various data types in C++. Knowing the right data type to use can optimize memory usage and improve program efficiency.
We delved into primitive types like integers, floats, and characters. We also examined derived types such as arrays, functions, pointers, and references. User-defined types like classes, structures, and unions were covered, showing how they help manage complex data.
Modifiers like signed, unsigned, short, and long were explained to understand how they affect data ranges and memory usage.
Mastering these concepts is crucial for writing efficient, error-free C++ code. Understanding data types helps us optimise memory and enhance program performance.
FAQs
What are the advantages of using enumerations in C++?
Enumerations enhance the organization of code and make it more readable and simplified.
Can we create our own data types in C++?
Yes, of course, data types can be created by individuals employing structures, classes, unions, and typedef.
How are pointers different from references in C++?
Pointers hold the memory address of a specific variable, while references are an alias of another variable.
What is the use of the void data type in C++?
The void data type is used for functions that do not return any value.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.