Skip to content

Instantly share code, notes, and snippets.

@mmomtchev
Last active June 19, 2024 15:37
Show Gist options
  • Save mmomtchev/b9f20d9da5e74f782591c19c07ed1a4b to your computer and use it in GitHub Desktop.
Save mmomtchev/b9f20d9da5e74f782591c19c07ed1a4b to your computer and use it in GitHub Desktop.
Gists for the C++ exceptions medium story
#include <stdexcept>
#include <stdio.h>
static int result;
int fibonacci(int i) {
// Optimize the branch prediction
if (i <= 1) [[unlikely]] {
if (i < 0)
throw std::runtime_error{"Negative number"};
if (i == 0)
return 0;
return 1;
}
try {
return fibonacci(i - 1) + fibonacci(i - 2);
} catch (const std::exception &) {
std::abort();
}
}
int main() {
try {
for (int i = 0; i < 45; i++) {
result = fibonacci(i);
}
} catch (const std::exception &) {
std::abort();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment