C++ Tutorial · C++ Basics · Lesson 4 of 21

C++ Variables and Data Types

Fundamental types, auto, const, constexpr and initialisation.

Create a free account to save this page, take notes and track your progress. Sign in

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>)
Example 1
#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.
  • auto deduces the type from the initialiser.
  • const values can't change; constexpr values 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?

  1. const
  2. constexpr
  3. static
  4. final
Show answer

Answer: constexpr

Was this page helpful?