Last active
June 19, 2024 15:37
-
-
Save mmomtchev/b9f20d9da5e74f782591c19c07ed1a4b to your computer and use it in GitHub Desktop.
Gists for the C++ exceptions medium story
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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