C++ provides several basic data types that allow you to store and manipulate different kinds of data. These data types can be broadly categorized into four groups: integral, floating-point, character, and boolean.
Integral types: These data types represent whole numbers, both positive and negative, without any fractional component. C++ provides the following integral data types:
char: used to store a single character. It is typically 8 bits in size and can hold values between -128 and 127 or 0 to 255 (if unsigned).
short: used to store small integers. It is typically 16 bits in size and can hold values between -32,768 and 32,767 or 0 to 65,535 (if unsigned).
int: used to store integers. It is typically 32 bits in size and can hold values between -2,147,483,648 and 2,147,483,647 or 0 to 4,294,967,295 (if unsigned).
long: used to store large integers. It is typically 64 bits in size and can hold values between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 or 0 to 18,446,744,073,709,551,615 (if unsigned).
Here’s an example of using some of the integral types in C++:
#include <iostream>
int main() {
char myChar = 'a';
short myShort = 42;
int myInt = 12345;
long myLong = 987654321;
std::cout << "Char: " << myChar << std::endl;
std::cout << "Short: " << myShort << std::endl;
std::cout << "Int: " << myInt << std::endl;
std::cout << "Long: " << myLong << std::endl;
return 0;
}
Floating-point types: These data types represent numbers with a fractional component. C++ provides two floating-point data types:
float: used to store single-precision floating-point numbers. It is typically 32 bits in size and can hold values with a precision of about 7 decimal digits.
double: used to store double-precision floating-point numbers. It is typically 64 bits in size and can hold values with a precision of about 15 decimal digits.
Here’s an example of using floating-point types in C++:
#include <iostream>
int main() {
float myFloat = 3.1415f;
double myDouble = 3.14159265358979323846;
std::cout << "Float: " << myFloat << std::endl;
std::cout << "Double: " << myDouble << std::endl;
return 0;
}
Character types: These data types represent single characters. C++ provides two character data types:
char: as mentioned earlier, used to store a single character.
wchar_t: used to store a wide character, which can represent characters from non-ASCII character sets.
Here’s an example of using character types in C++:
#include <iostream>
int main() {
char myChar = 'a';
wchar_t myWideChar = L'';
std::cout << "Char: " << myChar << std::endl;
std::wcout << "Wide Char: " << myWideChar << std::endl;
return 0;
}