# Modern C++

> The C++ the framework and its examples write where C would also compile — std::array, static_cast, enum class, nullptr, no varargs, fixed-width integers, ++i — and the C++20 the oldest compiler a game is built with can take.

Source: https://omardev29.github.io/rmp-docs/guidelines/modern-cpp.html

raylib is C, and the framework is C++ written on top of it. Where C++ has a way of saying something that knows more than C's — how long an array is, which conversion a cast means, which scope a name belongs to — the code here uses it, and a check holds it there. raylib's own types and calls stay as they are: a call into raylib is where the C++ ends, and that boundary is written down below wherever a rule meets it.

Each rule says why, shows the way the framework refuses and the way it takes, and names what checks it and where. "The framework" is its `include/`, `src/` and `tests/`; the examples have a `.clang-tidy` of their own; and a game made with `rmp new` gets none of these checks, only the advice. [What checks what](https://omardev29.github.io/rmp-docs/guidelines/enforcement.html) has every rule of these pages in one table.

## std::array, not a C array

A C array forgets its length the moment it is passed anywhere, and cannot be copied or returned. `std::array` knows its size, copies like any other value, and works with a range-for and the standard algorithms:

Compiles; `rmp lint` refuses it: `modernize-avoid-c-arrays`

```cpp
int high_scores[5] = {};
```

```cpp
#include <array>

std::array<int, 5> high_scores{};

int best() {
    int top = 0;
    for (const int score : high_scores) top = score > top ? score : top;
    return top;
}
```

raylib takes C arrays as a pointer and a count, and that call is the boundary: the array hands over `data()` and its size, converted to the `int` raylib asks for.

```cpp
const std::array corners{ Vector2{ 0, 0 }, Vector2{ 40, 0 }, Vector2{ 20, 30 } };
DrawTriangleFan(corners.data(), static_cast<int>(corners.size()), RED);
```

Let the compiler count when the list is the whole array. A size written by hand that is larger than the list compiles, and fills the rest with zeros, which no check notices; written without a size, the array is exactly as long as what is in it:

```cpp
#include <array>

constexpr std::array LANES{ 120.0f, 240.0f, 360.0f };
```

Checked by `modernize-avoid-c-arrays`, in the framework and in the examples.

## static_cast, never a C cast

A C cast does whatever it takes to make the types fit: a value conversion, a reinterpretation of the bits, a `const` thrown away. `static_cast` says which conversion was meant, does only that one, and is the one a reader can search for. Converting a `float` to an `int` is the usual case in a game, and it is the one a C cast hides best:

Compiles; `rmp lint` refuses it: `modernize-avoid-c-style-cast`

```cpp
int whole_seconds(float seconds) { return (int)seconds; }
```

```cpp
int whole_seconds(const float seconds) { return static_cast<int>(seconds); }
```

A conversion that cannot lose anything can be written with braces instead, which refuse to compile one that could. Google's guide prefers that form wherever it applies:

```cpp
#include <cstdint>

std::int64_t total(const int score) { return std::int64_t{ score } * 1000; }
```

clang-tidy parses one branch of every `#if`, the one of the machine it runs on, so a cast in the Android branch is invisible to a lint run on Linux. The style gate reads every branch:

Compiles; `rmp test style` refuses it: `S1`

```cpp
#if defined(PLATFORM_ANDROID)
const int columns = (int)(GetScreenWidth() / 64.0f);
#else
const int columns = static_cast<int>(GetScreenWidth() / 64.0f);
#endif
DrawRectangle(0, 0, columns, columns, RED);
```

Checked by `modernize-avoid-c-style-cast`, in the framework and in the examples, and by rule S1 of `tools/style_check.sh`, the `style` stage of `rmp test`, over every branch of the framework's and the examples' code. The plain C example and `tests/smoke_test.h`, which is compiled as C, are exempt: a cast is the language there.

## enum class

The members of a plain `enum` are names in the enclosing scope and turn into `int` without being asked: `LEFT` collides with the next enum that has a `LEFT`, and `LEFT + 3` compiles. An `enum class` keeps its members to itself, and converts only when a cast says so:

Compiles; `rmp lint` refuses it: `cppcoreguidelines-use-enum-class`

```cpp
enum Direction { LEFT, RIGHT };
```

```cpp
enum class Direction { LEFT, RIGHT };

int step(const Direction direction) { return direction == Direction::LEFT ? -1 : 1; }
```

raylib's enums — `KEY_SPACE`, `LOG_INFO` — are C's, and are used as raylib declares them. Checked by `cppcoreguidelines-use-enum-class`, in the framework and in the examples.

## nullptr, never NULL or 0

`NULL` and `0` are integers that happen to convert to a pointer, so an overload that takes an `int` can be chosen over the one that takes a pointer. `nullptr` has a type of its own and converts only to a pointer. The rule against raw pointers ([Pointers and RAII](https://omardev29.github.io/rmp-docs/guidelines/pointers-and-raii.html)) leaves it few places to appear, most of them where a C function asks for a pointer:

Compiles; `rmp lint` refuses it: `modernize-use-nullptr`

```cpp
#include <ctime>

std::time_t now() { return std::time(0); }
```

```cpp
#include <ctime>

std::time_t now() { return std::time(nullptr); }
```

Checked by `modernize-use-nullptr`, in the framework and in the examples, and `NULL` by rule S2 of `tools/style_check.sh`, in every branch.

## No C variadic functions

A function declared with `...` takes anything and checks nothing: the types of what it reads are whatever its body says they are, and a wrong one is undefined behaviour, not an error. A list of values of one type is a `std::span` (or an initializer list); values of several types are a template:

Compiles; `rmp lint` refuses it: `modernize-avoid-variadic-functions`

```cpp
#include <cstdarg>

int sum(int count, ...) {
    va_list values;
    va_start(values, count);
    int total = 0;
    for (int i = 0; i < count; ++i) total += va_arg(values, int);
    va_end(values);
    return total;
}
```

```cpp
#include <span>

int sum(std::span<const int> values) {
    int total = 0;
    for (const int value : values) total += value;
    return total;
}
```

A `std::array`, a `std::vector` or a braced list passes to it as it is. *Calling* raylib's variadic functions — `TraceLog()`, `TextFormat()` — is the boundary, and allowed: the rule is about defining one.

The framework defines two, on purpose, side by side: the functions behind its said-once warnings, which hand a `printf` format to `TraceLog()`, one of them with a key. Each carries a `NOLINT` with the reason, and a `format(printf)` attribute, so GCC and Clang check every format against its values as an error. [Macros](https://omardev29.github.io/rmp-docs/framework/why/macros.html#report-once) has the details. Checked by `modernize-avoid-variadic-functions`, in the framework and in the examples.

## int, and a fixed width when the size matters

How wide `long` is depends on the platform: 64 bits on 64-bit Linux and macOS, 32 on Windows and on the web. A game that ships to all of them has two different types under one name. `int` is the integer, and when a value needs a known size, `<cstdint>` names it:

Compiles; `rmp lint` refuses it: `google-runtime-int`

```cpp
long total_score = 0;
```

```cpp
#include <cstdint>

std::int64_t total_score = 0;
```

Unsigned types are for bits — a collision mask, a generation counter that is meant to wrap — and not for saying a number is never negative. `float` and `double` are the floating-point types; `long double` is a different size on every compiler:

Compiles; `rmp lint` refuses it: `google-runtime-float`

```cpp
long double elapsed = 0;
```

Checked by `google-runtime-int` and `google-runtime-float`, in the framework and in the examples. That an unsigned number is a bit pattern is a question for review.

## A one-argument constructor is explicit

A constructor that takes one argument is also a conversion, used wherever the compiler finds the argument's type and wants the class: a `float` passed where `Meters` is expected becomes one without a word. `explicit` makes that a decision of the caller's:

Compiles; `rmp lint` refuses it: `google-explicit-constructor`

```cpp
struct Meters {
    Meters(float value) : value(value) {}
    float value;
};
```

```cpp
struct Meters {
    explicit Meters(const float amount) : value(amount) {}
    float value;
};
```

The framework's API makes a few conversions on purpose, because without them the simple call would be longer: a number, a `bool` or a piece of text becomes an [`rmp::Value`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Value.html), so a save is filled the way it reads.

```cpp
rmp::Value save;
save["score"] = 3;
save["name"] = "Omar";
save["alive"] = true;
```

Each of those conversions carries a `NOLINT` and its reason beside it; [Google's guide and this one](https://omardev29.github.io/rmp-docs/guidelines/google.html#implicit-conversions) lists them. Checked by `google-explicit-constructor`, in the framework and in the examples.

## A class that manages something says what its copies do

A class that writes its own destructor is managing something, and the copy the compiler writes for it copies the handle and not the thing: two copies, two destructors, one thing released twice. A class that writes one of the destructor, the copy and the move says what becomes of the others:

Compiles; `rmp lint` refuses it: `cppcoreguidelines-special-member-functions`

```cpp
class Voice {
public:
    explicit Voice(const Sound sound) : _sound(sound) {}
    ~Voice() { StopSound(_sound); }

private:
    Sound _sound;
};
```

```cpp
class Voice {
public:
    explicit Voice(const Sound sound) : _sound(sound) {}
    Voice(const Voice &) = delete;
    Voice &operator=(const Voice &) = delete;
    ~Voice() { StopSound(_sound); }

private:
    Sound _sound;
};
```

A class whose copy is deleted is not asked for its moves, which go with it, and a lone `= default` destructor manages nothing and is not asked for anything. Checked by `cppcoreguidelines-special-member-functions`, in the framework and in the examples.

## auto where the type is already on the line

Google's rule: deduce a type only when that makes the code clearer to someone who does not know it. A cast already names the type, so writing it again on the left says it twice:

Compiles; `rmp lint` refuses it: `modernize-use-auto`

```cpp
const float width = static_cast<float>(GetScreenWidth());
DrawLineV(Vector2{ 0, 0 }, Vector2{ width, 0 }, RED);
```

```cpp
const auto width = static_cast<float>(GetScreenWidth());
DrawLineV(Vector2{ 0, 0 }, Vector2{ width, 0 }, RED);
```

Elsewhere the type is written: `const int lives = 3;` tells the reader something `auto` would make them work out. Checked by `modernize-use-auto` in the framework only — the examples switch the `modernize` family off, keeping only the rules this page names — and the rest of Google's rule is a question for review.

## using, not typedef

An alias reads left to right like an assignment, and can be a template; a `typedef` can be neither:

Compiles; `rmp lint` refuses it: `modernize-use-using`

```cpp
typedef int Score;
```

```cpp
using Score = int;
```

Checked by `modernize-use-using`, in the framework and in the examples.

## std::numbers, not a typed-in π

A constant typed in by hand is as precise as the hand that typed it. C++20 has them in `<numbers>`, exact to the type you ask for. raylib's `PI` is a macro, which is also why no constant of yours can be called that ([Macros](https://omardev29.github.io/rmp-docs/guidelines/macros.html#names)):

Compiles; `rmp lint` refuses it: `modernize-use-std-numbers`

```cpp
constexpr float HALF_TURN = 3.14159265f;
```

```cpp
#include <numbers>

constexpr float HALF_TURN = std::numbers::pi_v<float>;
```

Checked by `modernize-use-std-numbers`, in the framework and in the examples. It recognises a literal; a use of raylib's macro is not something it reports.

## ++i

Google's rule: `i++` promises the value from before the increment, and when nothing reads that value the promise is noise — and, for an iterator, a copy. The prefix form says what is meant:

Compiles; `rmp test style` refuses it: `S6`

```cpp
int lives = 3;
lives--;
DrawText(TextFormat("lives %i", lives), 10, 10, 20, RED);
```

```cpp
int lives = 3;
--lives;
for (int i = 0; i < lives; ++i) DrawCircle(20 + (i * 30), 20, 10, RED);
```

Where the old value is the point, the postfix form is the right one, and the gate lets it be:

```cpp
int next_id = 1;
const int id = next_id++;
TraceLog(LOG_INFO, "spawned %d, next %d", id, next_id);
```

Checked by rule S6 of `tools/style_check.sh`, in every branch of the framework and the examples; this site holds every block on its pages to the same rule.

## No user-defined literals

Google's rule. `"Pong"sv` and `10ms` are short, and each needs a `using namespace` to work, which brings every other name of that namespace with it. The type, written out, says the same thing to a reader who has never seen the suffix:

Compiles; `rmp test style` refuses it: `S5`

```cpp
#include <string_view>

using namespace std::string_view_literals;
constexpr auto TITLE = "Pong"sv;
```

```cpp
#include <string_view>

constexpr std::string_view TITLE = "Pong";
```

Checked by rule S5 of `tools/style_check.sh`, the standard library's literals included, in every branch of the framework and the examples.

## No using namespace

A using-directive pours a whole namespace into the file, names that arrive in a later version of the library included. Writing the namespace keeps every name's origin where it is used:

Compiles; `rmp lint` refuses it: `google-build-using-namespace`

```cpp
#include <vector>

using namespace std;

vector<int> scores;
```

```cpp
#include <vector>

std::vector<int> scores;
```

Checked by `google-build-using-namespace`, in the framework and in the examples.

## No default argument on a virtual function

A default argument belongs to the declaration the call is compiled against, not to the function that runs: called through the base class, an override gets the base's default whatever its own says. An overload that forwards says it once:

Compiles; `rmp lint` refuses it: `google-default-arguments`

```cpp
class Shape {
public:
    virtual ~Shape() = default;
    virtual void grow(float by = 1.0f) = 0;
};
```

```cpp
class Shape {
public:
    Shape() = default;
    Shape(const Shape &) = delete;
    Shape &operator=(const Shape &) = delete;
    virtual ~Shape() = default;
    void grow() { grow(1.0f); }
    virtual void grow(float by) = 0;
};
```

Checked by `google-default-arguments`, in the framework and in the examples.

## std::span and std::optional instead of a pointer

A pointer and a count are a `std::span`, which carries both and cannot be given one without the other. A result that may not be there is a `std::optional`, which says so in its type instead of in a comment about `-1`:

Compiles; `rmp lint` refuses it: `custom-rmp-raw-pointer`

```cpp
int total(const int *values, int count) {
    int sum = 0;
    for (int i = 0; i < count; ++i) sum += values[i];
    return sum;
}
```

```cpp
#include <optional>
#include <string_view>

std::optional<int> level_number(const std::string_view name) {
    if (name.size() != 7 || !name.starts_with("level_")) return std::nullopt;
    return name.back() - '0';
}
```

[Pointers and RAII](https://omardev29.github.io/rmp-docs/guidelines/pointers-and-raii.html) has the rest: a reference that may be empty is an [`rmp::Ref`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Ref.html), and an object kept across frames is an [`rmp::Handle`](https://omardev29.github.io/rmp-docs/reference/classes/rmp-Handle.html). Checked by `custom-rmp-raw-pointer`, a query of the framework's own `.clang-tidy`, in the framework and in the examples.

## Designated initialisers, in declaration order

The options of every call in the API are a struct written with designated initialisers, and C++20 wants them in the order the fields are declared. GCC and MSVC refuse them out of order; Clang only warns, so the framework hands every target that links it the flag that makes Clang refuse too — a game's included:

Does not compile

```cpp
struct Point {
    float x = 0;
    float y = 0;
};
const Point p{ .y = 2, .x = 1 };
DrawCircleV(Vector2{ p.x, p.y }, 4, RED);
```

The compiler refuses it, saying among other things: `declaration order`

```cpp
struct Point {
    float x = 0;
    float y = 0;
};
const Point p{ .x = 1, .y = 2 };
DrawCircleV(Vector2{ p.x, p.y }, 4, RED);
```

Checked by the compiler, with `-Werror=reorder-init-list` under Clang, everywhere: the framework, the examples and a game. [Designated initialisers](https://omardev29.github.io/rmp-docs/framework/why/designated-initialisers.html) has why the fields are ordered the way they would be written.

## C++20, as the oldest compiler speaks it

A game is built for every target from the same sources, and the oldest compiler among them is NetBSD's GCC 10.5. It takes the C++20 the framework is written in — `std::span`, `std::optional`, concepts through `requires`, designated initialisers, `<numbers>`, `constinit` — and not what arrived in GCC 11 and later: `<format>`, `<source_location>`, `std::bit_cast`, `using enum`, and what C++23 added. A use of one compiles on a laptop and fails on NetBSD, in CI:

Compiles; `rmp test style` refuses it: `S4`

```cpp
#include <bit>
#include <cstdint>

std::uint32_t bits_of(const float value) { return std::bit_cast<std::uint32_t>(value); }
```

```cpp
#include <cstdint>
#include <cstring>

std::uint32_t bits_of(const float value) {
    std::uint32_t bits = 0;
    std::memcpy(&bits, &value, sizeof bits);
    return bits;
}
```

The same compiler reports `__cplusplus` as `201709L` under `-std=c++20`, because C++20 was not final when it shipped: test for a feature, not for the version number. Checked by rule S4 of `tools/style_check.sh`, in every branch of the code a game compiles: `include/`, `src/` and the examples. The framework's tests build only on the CI image's compilers and are exempt.
