C++ Tutorial · C++ Basics · Lesson 4 of 21
C++ Variables and Data Types
Fundamental types, auto, const, constexpr and initialisation.
Fundamental types
| Type | Example |
|---|---|
int, long long |
42, 9'000'000'000LL |
double, float |
3.14, 2.5f |
bool |
true |
char |
'A' |
std::string |
"text" (from <string>) |
#include <iostream>
#include <limits>
#include <string>
int main() {
int age{36};
double height = 1.68;
char grade = 'A';
bool active = true;
std::string name = "Ada";
auto population = 8'100'000LL; // long long
const double pi = 3.14159;
constexpr int squares = 12 * 12; // computed at compile time
std::cout << name << ' ' << age << ' ' << height << ' ' << grade << ' ' << active << '\n';
std::cout << population << ' ' << pi << ' ' << squares << '\n';
std::cout << 7 / 2 << ' ' << 7 / 2.0 << ' ' << static_cast<double>(7) / 2 << '\n';
std::cout << sizeof(int) << ' ' << sizeof(double) << ' ' << std::numeric_limits<int>::max() << '\n';
}
Output
Ada 36 1.68 A 1 8100000 3.14159 144 3 3.5 3.5 4 8 2147483647
Run this on your computer — see “Get Started” for setup.
- Brace initialisation
int x{5};prevents narrowing conversions. autodeduces the type from the initialiser.constvalues can't change;constexprvalues are computed at compile time.
Type conversion
Use static_cast<T>(value) for explicit conversions — it's searchable and safer than C-style casts.
Test yourself
Which keyword computes a constant at compile time?
constconstexprstaticfinal
Show answer
Answer: constexpr