C++C++

C++: Basics – code examples

Contents

Hello World

Basics#cout#main#output#includeCompare in all languages
Use case: A first test of whether the compiler and environment work.
#include <iostream>

int main() {
    std::cout << "Hello World!\n";
}

std::cout writes to the console, main is the entry point. Compile with g++ -std=c++20 hallo.cpp -o hallo.

Variables and types

Basics#variable#type#autoCompare in all languages
Use case: Store and print values with a fixed type.
#include <iostream>
#include <string>

int main() {
    std::string name = "Ada";
    int alter = 36;
    double groesse = 1.68;
    bool aktiv = true;
    auto n = 42;   // type is deduced: int
    std::cout << name << " " << alter << " " << groesse << " " << aktiv << " " << n << '\n';
}

C++ is statically typed; auto deduces the type from the value. A bool is printed as 1 or 0 (as true/false with std::boolalpha).

enum class and switch

Basics#enum#enum class#switch
Use case: Name states or options in a type-safe way, e.g. game states or log levels.
#include <iostream>

enum class Ampel { Rot, Gelb, Gruen };

const char* aktion(Ampel a) {
    switch (a) {
        case Ampel::Rot:   return "wait";
        case Ampel::Gelb:  return "get ready";
        case Ampel::Gruen: return "go";
    }
    return "?";
}

int main() { std::cout << aktion(Ampel::Gruen) << '\n'; }

enum class has its own namespace and does not convert implicitly to int. The compiler warns (-Wall) if a case is missing in the switch.