Modern C++ Fundamentals: From Basics to Smart Pointers and Threads · Modern C++ Basics: Types, Containers, Functions and Classes

Hello, C++: Building, Types and Formatting

Compile and run a C++ program, use the core types with auto and const, read the standard library's std::format, and learn the habits that keep modern C++ safe.

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

What you'll build

A small fuel-cost calculator. You'll compile it, declare typed variables with const and auto, format numbers with std::format, and meet the warnings flags that catch mistakes.

The idea

C++ is a compiled language for programs where speed and control matter: games, browsers, databases, embedded devices, trading systems. It gives you high-level tools (containers, algorithms, classes) with no runtime or garbage collector, so you decide how memory is used.

Compile and run with a recent compiler (this course uses C++20):

g++ -std=c++20 -Wall -Wextra -O2 main.cpp -o app
./app

-Wall -Wextra turn on helpful warnings; read them. Larger projects use CMake, but one file and g++ are enough to learn.

Core ideas:

  • Every program starts at main. #include <iostream> brings in the library; std::cout << value prints, and '\n' ends a line.
  • Types: int, long, double, bool, char, std::string. Integers have limited ranges; floating point is approximate.
  • const says a value never changes. Make things const by default.
  • auto lets the compiler deduce a variable's type from its initializer: auto total = 12.5; is a double.
  • Initialization: prefer brace initialization int count{3};; it refuses narrowing conversions (int x{3.5}; does not compile).
  • std::format (C++20) builds text with {} placeholders and format specs like {:.2f}.

The code

A fuel-cost calculator with const, auto and std::format
#include <format>
#include <iostream>
#include <string>

int main() {
    const std::string car{"Hatchback"};
    const double distance_km{245.5};
    const double litres_per_100km{6.4};
    const double price_per_litre{1.79};
    int passengers{3};

    const auto litres = distance_km / 100.0 * litres_per_100km;   // auto: double
    const auto cost = litres * price_per_litre;
    const auto per_person = cost / passengers;

    std::cout << std::format("{} trip: {:.1f} km\n", car, distance_km);
    std::cout << std::format("fuel: {:.2f} L, cost: {:.2f}\n", litres, cost);
    std::cout << std::format("per person ({}): {:.2f}\n", passengers, per_person);

    // Integer division truncates; mixing in a double avoids it
    std::cout << "7 / 2 = " << 7 / 2 << ", 7 / 2.0 = " << 7 / 2.0 << '\n';

    // Brace initialisation rejects narrowing conversions:
    // int whole{distance_km};   // error: narrowing conversion of a double to int
    int whole = static_cast<int>(distance_km);   // an explicit, visible conversion
    std::cout << "whole km: " << whole << '\n';
}

Output

Hatchback trip: 245.5 km
fuel: 15.71 L, cost: 28.12
per person (3): 9.37
7 / 2 = 3, 7 / 2.0 = 3.5
whole km: 245

Run this on your computer — see “Get Started” for setup.

Uncomment the int whole{distance_km}; line and the compiler stops with a narrowing error, where older C-style code would silently lose the decimals.

Common mistakes

  • Not compiling with warnings. -Wall -Wextra is free and finds real bugs.
  • Uninitialized variables. int count; holds garbage. Always give a value: int count{}; is zero.
  • Integer division surprises. 7 / 2 is 3. Use a double operand when you need a fractional result.
  • Writing using namespace std; in headers. It pollutes every file that includes yours. Qualify names with std::.
  • Treating float and double as exact. Use integers (cents) for money, and compare doubles with a tolerance.

Key points

  • Compile with g++ -std=c++20 -Wall -Wextra; read the warnings.
  • Prefer const, auto for obvious types, and brace initialization.
  • std::format provides safe, readable formatting; integer division truncates.
  • Convert types explicitly (static_cast) when you mean to narrow.

Further reading: cppreference: std::format.

Practice questions

Why does `int x{3.5};` not compile while `int x = 3.5;` does?

Answer

Brace initialization forbids narrowing conversions, so converting a double to an int is an error. Copy initialization with = allows the conversion and silently truncates to 3.

What does `auto` do, and when should you avoid it?

Answer

auto deduces a variable's type from its initializer, saving repetition. Avoid it where the type isn't obvious from the right-hand side, or where you need a specific type (for example to force an integer or a particular width).

Open in the app to mark lessons complete, take notes and track your progress.

Was this page helpful?