C++C++
BeginnerLesson 2 of 18

Variables, Types and const – C++

Basic types, type inference with auto, safe initialization and constants.

C++ is statically typed: every variable has a fixed type that is known at compile time. With auto, you let the compiler deduce the type from the initial value.

#include <iostream>
#include <string>

int main() {
    int alter = 36;              // integer
    double groesse = 1.68;       // floating-point number
    bool aktiv = true;           // boolean value
    char buchstabe = 'A';        // single character
    std::string name = "Ada";    // text
    auto anzahl = 10;            // int (deduced)
    const double PI = 3.14159;   // immutable

    std::cout << name << " " << alter << " " << groesse << " " << aktiv << '\n';
    std::cout << sizeof(int) << " Bytes, PI = " << PI << '\n';
}

Prefer initialization with curly braces {}: it forbids lossy conversions ("narrowing") and initializes empty braces with 0.

int a{42};
// int b{3.7};     // error: narrowing from double to int
int c = 3.7;       // allowed, but c == 3 (truncated)
int d{};           // d == 0

std::cout << 7 / 2 << " " << 7 / 2.0 << " " << 7 % 2 << '\n';   // 3 3.5 1

constexpr int TAGE = 7;    // value is already fixed at compile time
const int n = 5;           // value is fixed, but may be computed at runtime
  • int, long, long long – integers (size depends on the platform; fixed sizes: std::int32_t, std::uint64_t from <cstdint>)
  • float, double – floating point (the default is double)
  • unsigned types simply wrap around on overflow, int does not (see pitfalls)
  • std::size_t is the type for sizes and indices (v.size() returns it)
WarningLocal variables without an initial value (int x;) contain garbage. Reading them triggers undefined behavior. So always initialize. With int divided by int, integer division is used: 7 / 2 is 3, not 3.5.