In Python or JavaScript, you can create a variable and never mention its type. In C++, that's simply not allowed — every variable needs a declared type before you can use it, and the compiler checks this before your program ever runs.
Declaring a variable
int age = 25;
double price = 9.99;
char grade = 'A';
bool isActive = true;Notice char uses single quotes for one character, while text made of several characters uses a completely different type, std::string, with double quotes:
#include <string>
std::string name = "Sam";What "compiled" actually means here
Unlike Python, which reads and runs your code line by line, C++ code has to be compiled first — translated entirely into machine code before it can run at all. This step is exactly where type mistakes get caught. Try to assign text to an int variable, and the compiler will refuse to build your program at all, rather than letting it run and fail unexpectedly later, which is genuinely one of C++'s more helpful traits once you get used to it.
The common types you'll actually use
- int — whole numbers.
- double — decimal numbers, more precise than float, and the more common default choice.
- char — a single character.
- bool — true or false.
- std::string — text, once you've included the string header.
const: locking a value down
const double PI = 3.14159;Marking a variable const tells both the compiler and anyone reading your code that this value is never meant to change after it's set. Try to reassign it, and the compiler stops you, which is a small habit that prevents a surprising number of real bugs.
A gotcha with integer division
int a = 7;
int b = 2;
std::cout << a / b; // prints 3, not 3.5Dividing two integers in C++ gives you an integer result, throwing away anything after the decimal point, even if you were hoping for a precise answer. To get 3.5 here, at least one of the values needs to actually be a double.
Why all this rigidity is worth it
It feels like more upfront work compared to a language that just figures types out for you. But that rigidity is exactly what lets the compiler catch a whole category of mistakes before your program ever runs, and it's a big part of why well-written C++ programs can be both extremely fast and, once compiled successfully, surprisingly reliable.