This tutorial aims to provide a basic understanding of data types in C++. The primary goal is to familiarize you with how to declare variables or functions of different types in C++.
By the end of this tutorial, you will have a clear understanding of various data types in C++, how to use them, and the best practices associated with them.
Prerequisites: Basic knowledge of C++ programming.
Data types in C++ can be broadly classified into three types: built-in, user-defined, and derived.
Built-in types are those that are predefined and can be used directly by the user. They include:
int
, short
, long
, long long
)float
, double
, long double
)char
, char16_t
, char32_t
, wchar_t
)bool
)void
)nullptr
)User-defined types include:
- Class
- Structure
- Union
- Enumeration
- Typedef defined types
Derived types include:
- Array
- Function
- Pointer
- Reference
Integer types can represent a set of positive and negative numbers including zero. Here is an example:
int x = 10; // declaring an integer variable
Floating-point types can represent real numbers, such as 0.95 or -123.45, i.e., they can represent numbers that have a decimal point. Here is an example:
float y = 10.5; // declaring a floating-point variable
#include <iostream>
using namespace std;
int main() {
int a = 10; // integer
char b = 'A'; // character
bool c = true; // boolean
float d = 20.5; // float
double e = 30.123456789; // double
cout << "Integer: " << a << endl;
cout << "Character: " << b << endl;
cout << "Boolean: " << c << endl;
cout << "Float: " << d << endl;
cout << "Double: " << e << endl;
return 0;
}
This code declares five variables of different data types, assigns them values, and then prints them. The expected output is:
Integer: 10
Character: A
Boolean: 1
Float: 20.5
Double: 30.1235
This tutorial covered the basics of data types in C++, including built-in, user-defined, and derived types. You learned how to declare variables of different types, and how to use them in your code.
For further study, I recommend exploring each data type in more detail, especially the user-defined and derived types. You can also try to solve some problems that require you to use different data types.
int x = 5;
int y = 10;
int sum = x + y;
cout << "The sum is " << sum << endl;
char c = 'B';
cout << "The character is " << c << endl;
bool isCodingFun = true;
cout << "Is coding fun? " << isCodingFun << endl;