C++ 17 - [[fallthrough]] attribute

cpp, C++17, fallthrough

Start at work to use a compiler that supports the standard C++17.

Actively we begin to use various features from this standard..

I was pleased with the [[fallthrough]] attribute for switch case constructions.

The essence of this attribute is that it indicates that the break statement was intentionally omitted in the switch case construction and that this is not a programmer's mistake.

The fact is that the switch case construction allows the end-to-end execution of the program code through all the choices of case, if the break statement has not been added.

Here is the classic version of this design.

int x = 100;
 
bool check_x()
{
    switch (x)  
    {
        case 0:
            return true;
        case 50:
            x = 0:
            break;
        case 100:
            return false;
        default:
            return false;
    }
}

But the variant with the end-to-end execution of the code when the break statement is omitted.

int x = 100;
 
bool check_x()
{
    switch (x)  
    {
        case 0:
        case 50:
        case 100:
            return true;
        default:
            return false;
    }
}

In this case, the same code will be executed for all values 0, 50, 100. But at the same time, the compiler may issue a prerequisite, and other programmers who may support your program code in the future may consider this an error.

To indicate that the omission of the break statement was made intentionally, the fallthrough attribute was entered,. And then this program code will look like this.

int x = 100;
 
bool check_x()
{
    switch (x)  
    {
        case 0:
            [[fallthrough]];
        case 50:
            [[fallthrough]];
        case 100:
            return true;
        default:
            return false;
    }
}

You can also inform the compiler that the default operator was also intentionally omitted.

int x = 100;
 
bool check_x()
{
    switch (x)  
    {
        case 0:
            [[fallthrough]];
        case 50:
            [[fallthrough]];
        case 100:
            return true;
        case 105:
            [[fallthrough]];
    }
    return false;
}

In general, a very useful thing, which removes discrepancies and the human factor.






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.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Looking for a Job?
25,000.00 руб. - 30,000.00 руб.
Разработчик Qt/C++
Barnaul, Altai Krai, Russia

For registered users on the site there is a minimum amount of advertising

z
Sept. 14, 2019, 7:30 a.m.
zhdv06

C++ - Test 001. The first program and data types

  • Result:93points,
  • Rating points8
AQ
Sept. 13, 2019, 1:49 p.m.
Ask Questions

C++ - Test 005. Structures and Classes

  • Result:83points,
  • Rating points4
B
Sept. 12, 2019, 3:42 a.m.
Baobab

C++ - Test 005. Structures and Classes

  • Result:58points,
  • Rating points-2
Last comments
Sept. 14, 2019, 5:08 p.m.
Misha Lebedev

Приветствую вас Евгений , давно наблюда за развитием вашего замечательного портала, много полезно тут нашел , переодически зачитываюсь. Теперь по сушеству, делаю портал и там идеально ложи…
Sept. 10, 2019, 4:38 p.m.
Evgenij Legotskoj

function view для модели Article и LikeDislike.LIKE будет выглядеть так def like(request, pk): obj = Article.objects.get(pk=pk) try: likedislike = LikeDislike.objects.get(cont…
OK
Sept. 10, 2019, 4:10 p.m.
Oliver Kolesnikov

тут view написан в class based view, если честно ничего не могу разобрать. Как это всё переписать в function view?
o
Sept. 4, 2019, 3:54 a.m.
omortie

thanks for the application, it helps me a lot
Sept. 1, 2019, 2:51 p.m.
Evgenij Legotskoj

Добрый день, Александр. Это Forward Declaration - Предварительное объявление. Позволяет объявить класс без подключения заголовочного файла в заголовочном файле другого класса. Такое об…
Now discuss on the forum
R
Sept. 16, 2019, 7:09 a.m.
RED_Spider

прочитайте https://doc.qt.io/archives/qt-5.11/osx-deployment.html QMAKE_POST_LINK += "~/Qt/5.12.0/clang_64/bin/macdeployqt $${TARGET}.app $$escape_expand( \\n\\t )"
Sept. 16, 2019, 6:41 a.m.
Mihailll

Метод toASCII нельзя применить, а .toHex возвращает block: "000b0500000006006100610061" Но тут есть как минимум несколько букв. Как можно получить не цифры, а текст с цифрами?
M
Sept. 16, 2019, 2:51 a.m.
Mark

У класса есть метод AddPath(). Можно ли передать URL.
p
Sept. 15, 2019, 7:10 a.m.
pstMem

Всем привет При выполнении кода под отладкой msvc x64 через некоторое время работы получаю ошибку assert failure in qlist, приложение вылетает. Как правильно настроить qt чтобы при данной о…
Sept. 14, 2019, 8:13 a.m.
Mihailll

Можно использовать Flickable, растнянуть на него картинку и двигать
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB