Evgenii Legotckoi
Evgenii LegotckoiJan. 2, 2018, 4:33 a.m.

C ++ - Tutorial 012. static_assert, checking for errors at compile time

Content

Exceptions are thrown during the execution of the program; if the error can be found at compile time, you can use static_assert , which tells you to correct the program code in key locations.

The use of static_assert will look like this.

static_assert(4<=sizeof(int), "integers are too small"); // checking the size of an integer

The syntax is as follows: static_assert(A, B); Where

  • A - this is the condition under which the error will be thrown in the event that A is false
  • B - this is the text of the error message

Using

static_assert can be useful when using constants and constant expressions that are evaluated at compile time.

This code checks the local constant rate, which can not be faster than the speed of light.

constexpr double C = 299792.458; // km/s, speed of light

void f(double speed)
{
    const double local_max = 160.0/(60∗60); // 160 km/h == 160.0/(60*60) km/s
    static_assert(speed<C,"can't go that fast"); // error: speed must be a constant
    static_assert(local_max<C,"Can not move faster"); // OK
}

You can also use this check at key locations for transfers. For example, such an enumeration is given.

enum Types
{
    E_BEGIN_TYPES,
        E_A = E_BEGIN_TYPES,
        E_B,
        E_C,
        E_D,
    E_END_TYPES = E_D
};

And there is the following method or function in some place code

QString getStandardMessage(Types type)
{
    static_assert(E_END_TYPES == 3, "Need to implement method for new type");

    switch (type)
    {
        case E_A: return "Type A";
        case E_B: return "Type B";
        case E_C: return "Type C";
        case E_D: return "Type D";
        default: return "Type is not implemented";
    }
}

In this case, we know that the most recent enumeration, that is, E_D or E_END_TYPES is equal to 3. And an exception at compile time will not be thrown. But as soon as a new member of this enumeration is added.

enum Types
{
    E_BEGIN_TYPES,
        E_A = E_BEGIN_TYPES,
        E_B,
        E_C,
        E_D,
        E_E, // Новый участник перечисления
    E_END_TYPES = E_E
};

That static_assert will throw an error, which will mean that we forgot to correct this method. Correction will look like this.

QString getStandardMessage(Types type)
{
    static_assert(E_END_TYPES == 4, "Need to implement method for new type");

    switch (type)
    {
        case E_A: return "Type A";
        case E_B: return "Type B";
        case E_C: return "Type C";
        case E_D: return "Type D";
        case E_E: return "Type E";
        default: return "Type is not implemented";
    }
}

In this method, we add the implementation of the code for type E_E , and also correct the static_assert itself, so that it takes into account the number of enumeration participants with the new participant.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
i
innorwallNov. 14, 2024, 10:42 p.m.
How to Copy Files in Linux If only females relatives with DZ offspring were considered these percentages were 23 order priligy online uk
i
innorwallNov. 14, 2024, 8:09 p.m.
Qt/C++ - Tutorial 068. Hello World using the CMAKE build system in CLion ditropan pristiq dosing With the Yankees leading, 4 3, Rivera jogged in from the bullpen to a standing ovation as he prepared for his final appearance in Chicago buy priligy pakistan
i
innorwallNov. 14, 2024, 3:05 p.m.
EVILEG-CORE. Using Google reCAPTCHA 2001; 98 29 34 priligy buy
i
innorwallNov. 14, 2024, 3 p.m.
PyQt5 - Lesson 007. Works with QML QtQuick (Signals and slots) priligy 30mg Am J Obstet Gynecol 171 1488 505
i
innorwallNov. 14, 2024, 1:54 p.m.
Django - Tutorial 003. Model, Template, View on Django Hair follicles are believed to produce approximately 20 individual hair shafts over the life of the follicle as the follicle progresses through cycles of hair production, shedding ejection, invo…
Now discuss on the forum
i
innorwallNov. 14, 2024, 2:39 p.m.
добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
i
innorwallNov. 11, 2024, 9:55 p.m.
Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
9
9AnonimOct. 25, 2024, 7:10 p.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks