C++ data types are used to specify the type of data that a variable can store. There are many different data types in C++, each with its own purpose.
Here is a table of the most common C++ data types, along with examples:
|
Data type |
Description |
Example |
|
int |
Integer numbers |
int my_integer = 10; |
|
float |
Floating-point numbers |
float my_float = 3.14; |
|
double |
Double-precision floating-point numbers |
double my_double = 1234.5678; |
|
char |
Single characters |
char my_char = 'a'; |
|
string |
Character strings |
std::string my_string = "Hello, world!"; |
|
bool |
Boolean values (true or false) |
bool my_bool = true; |
You can also use the enum keyword to define your own custom data types. For example, the following code defines an enumeration called Color with the values red, green, and blue:
enum Color {
red,
green,
blue
};
You can then use the Color enumeration to declare variables:
Color my_color = Color::red;
This will declare a variable named my_color of type Color and initialize it to the value red.
Choosing the right data type
When choosing a data type for a variable, it is important to consider the type of data that the variable will store. For example, if you need to store an integer number, you should use the int data type. If you need to store a floating-point number, you should use the float or double data type.
It is also important to consider the size of the data type. For example, the int data type can store a smaller range of numbers than the long data type. However, the int data type is also more efficient to use.
Example
The following example shows how to use different data types in C++:
#include <iostream>
int main() {
// Declare variables of different data types.
int my_integer = 10;
float my_float = 3.14;
double my_double = 1234.5678;
char my_char = 'a';
std::string my_string = "Hello, world!";
bool my_bool = true;
// Print the values of the variables to the console.
std::cout << my_integer << std::endl;
std::cout << my_float << std::endl;
std::cout << my_double << std::endl;
std::cout << my_char << std::endl;
std::cout << my_string << std::endl;
std::cout << my_bool << std::endl;
return 0;
}
Output:
10
3.14
1234.5678
a
Hello, world!
true