← Retour au cours: Modern C++ from scratch

auto, constants and week 1 review

Vidéo bientôt disponible

To close the first week we look at two tools that make code safer and shorter: type deduction with auto and constants with const and constexpr. Then we review everything with a small program and a quiz. The central idea is always the same: tell the compiler as much as possible about your intentions so that it protects you from mistakes.

auto: let the compiler deduce the type

With auto, the compiler takes the type from the initial value. auto n = 42; creates an int; auto x = 3.14; creates a double; auto c = 'z'; creates a char. The variable still has a fixed, static type: auto is not a dynamic type, it just saves you typing it. It is very useful when the type is long (later, container iterators) and it avoids repeating obvious information. But be careful: auto needs an initial value, and the deduced type may surprise you, for example auto s = "hello"; deduces const char*, not std::string. To get a string use auto s = std::string{"hello"}; or the literal with suffix "hello"s after using namespace std::string_literals;.

cpp
#include <iostream>
#include <string>

int main() {
    auto count = 10;                 // int
    auto rate = 0.5;                 // double
    auto letter = 'x';               // char
    auto name = std::string{"Ada"}; // std::string
    auto total = count * rate;       // double * int -> double

    std::cout << name << " has " << count << " items\n";
    std::cout << "total = " << total << '\n';
    std::cout << "letter = " << letter << '\n';
    return 0;
}

const and constexpr

A const variable cannot be modified after initialization; if you try, the program does not compile. Use it by default for everything that does not need to change: it makes code easier to reason about. constexpr goes a step further: it requires the value to be known at compile time, so it can be used where a constant is needed, such as an array size. Practical rule: if the value is a fixed number or text known when you write the program, use constexpr; if it is computed at run time but does not change, use const.

cpp
#include <iostream>

constexpr double kVatRate = 0.21;   // known at compile time

int main() {
    const double net = 100.0;                 // fixed once initialized
    const double gross = net * (1.0 + kVatRate);

    // net = 120.0;   // error: assignment of read-only variable

    std::cout << "net = " << net << '\n';
    std::cout << "gross = " << gross << '\n';
    return 0;
}

Week review

This week you learned to install a compiler, compile with g++ -std=c++20, use std::cout, declare variables of the basic types, initialize them with braces, avoid accidental integer division, and use auto, const and constexpr. I recommend retyping every example yourself, without copy and paste: your fingers learn too. Cause deliberate errors (forget a semicolon, change a const) and read the compiler messages until they stop scaring you.

A frequent mistake with auto is expecting it to guess your intention. If you write auto x = 5 / 2;, x is an int with value 2, because both operands are integers and the division discards the decimal part; auto does not change that. To get 2.5 you must write 5.0 / 2 or use static_cast<double>. In the same way, auto n = 0; creates an int even if later you want to store a large number. When the type matters, write it explicitly or use a suffix on the literal (0L, 1.5f).

Testez vos acquis

Question 1 sur 6

What does main() normally return to signal that everything went well?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →