cpp / intermediate
Snippet
Intentional Switch Fallthrough
Switch fallthrough occurs when a case doesn't end with a break. While often a bug, it can be useful for hierarchical logic. The [[fallthrough]] attribute explicitly tells the compiler and other developers that this behavior is intended.
snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>void handlePermissions(int securityLevel) {switch (securityLevel) {case 3:std::cout << "Admin rights granted.\n";[[fallthrough]]; // C++17 attribute to suppress warningscase 2:std::cout << "Editor rights granted.\n";[[fallthrough]];case 1:std::cout << "Viewer rights granted.\n";break;default:std::cout << "Access denied.\n";}}
Breakdown
1
[[fallthrough]];
An attribute indicating that moving to the next case without a break is intentional.