Introduction to Fundamental Data Types in C++.

Introduction

Understanding data types is akin to learning the alphabet before constructing sentences. Fundamental data types form the foundation of variable declarations, determining the nature of the information a program can store and manipulate. In this chapter, we will explore the fundamental data types in C++, shedding light on their characteristics and use cases.

Variables: The Building Blocks

A variable is a named storage location capable of holding data. Before delving into the specifics of data types, let's first grasp the concept of variables.

int age; // declares an integer variable name "age"

Here, int is a data type indicating that the variable age will store integer values. C++ offers a variety of fundamental data types to cater to different types of information.

1️⃣Integer Types

int: This is the most commonly used integer type in C++. It typically occupies 4 bytes of memory, which is architecture specific. It can store values ranging from -2147483648 to 2147483647.

int number = 7;

short and long: These are variations of the int type, occupying less or more memory, respectively. Their usage depends on the range of values you anticipate for a variable.

short smallNumber = 10;
long bigNumber = 1234567890;

2️⃣Floating-Pont Types

float and double: These are used for representing real numbers. float is a single-precision type, while double is double-precision, offering more precision but using more memory.

float pi = 3.14;
double gravity = 9.81;

3️⃣Character Types

char: Used to store individual characters, such as letters or symbols.

char grade = 'A';

4️⃣Boolean Type

bool: Reserved for Boolean values representing true or false.

bool isHot = true;

5️⃣Void Type

void: The `void data type id special because it is used to indicate that a function does not return any value. It is typically used in the function declaration to signify that the function performs a tasks but doesn't produce a result. Void represents the absence of a type.

void greetUser() {
    cout << "Hello, User!" << endl;
}

In this example, the greetUser function has a void return type, indicating that it doesn't return any value.

Additionally, the void type is commonly used in the context of pointers. A void pointer, also known as a generic pointer, is a pointer that can point to objects of any data type. This flexibility makes it a powerful tool when dealing with memory allocation and manipulation.

void* genericPointer;

int integerValue = 10;
genericPointer = &integerValue;

double doubleValue = 3.14;
genericPointer = &doubleValue;

Understanding Size and Range

It's crucial to be mindful of the size and range of each data type especially when dealing with memory constraints or the potential for overflow. The sizeof() operator can be employed to determine the size of a variable in bytes.

cout << "Size of int: " << sizeof(int) << " bytes" << endl;