C++ Data Types
Every variable in C++ has a data type, which decides what kind of value it can hold, how much memory it uses, and what operations you can perform on it. Choosing the right type keeps your programs correct and efficient.
Basic Data Types
C++ comes with several built-in, or primitive, data types. The ones you will use most often are int for whole numbers, double for decimals, char for single characters, bool for true/false values, and string for text (which comes from the standard library).
Different types in one program
#include <iostream>
#include <string>
using namespace std;
int main() {
int quantity = 3;
double price = 4.50;
char grade = 'B';
bool inStock = true;
string item = "Notebook";
cout << item << " x" << quantity << endl;
cout << "Price each: " << price << endl;
cout << "Grade: " << grade << endl;
cout << "In stock: " << inStock;
return 0;
}Checking a Type's Size
Each type takes up a certain amount of memory, measured in bytes. The sizeof operator lets you see how big a type is on your system. Sizes can vary between machines, but the relative order is stable.
Using sizeof
#include <iostream>
using namespace std;
int main() {
cout << "int: " << sizeof(int) << " bytes" << endl;
cout << "double: " << sizeof(double) << " bytes" << endl;
cout << "char: " << sizeof(char) << " byte";
return 0;
}- Use int when you only need whole numbers.
- Use double when you need fractional values.
- Use char for a single letter or symbol.
- Use bool for yes/no or on/off style values.
Exercise: C++ Data Types
What does the bool data type represent in C++?