From 730633f15a176af90ee4aedc169ba581df0d3b2f Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Wed, 18 Oct 2023 20:29:41 +0200 Subject: [PATCH] feat: test constexpr --- CMakeLists.txt | 3 ++- src/constexp.cpp | 27 +++++++++++++++++++++++++++ src/constexp.h | 5 +++++ src/main.cpp | 6 ++++++ 4 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 src/constexp.cpp create mode 100644 src/constexp.h diff --git a/CMakeLists.txt b/CMakeLists.txt index c543d70..dfc39b8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,8 @@ include(ExportCompileCommands) configure_file("${PROJECT_SOURCE_DIR}/include/version.h.in" "${PROJECT_BINARY_DIR}/include/version.h") -add_executable(hello src/main.cpp src/null.cpp) +add_executable(hello src/main.cpp src/null.cpp src/constexp.cpp) + target_compile_features(hello PUBLIC cxx_std_20) target_include_directories(hello PRIVATE "${PROJECT_BINARY_DIR}/include") diff --git a/src/constexp.cpp b/src/constexp.cpp new file mode 100644 index 0000000..f0a5d73 --- /dev/null +++ b/src/constexp.cpp @@ -0,0 +1,27 @@ +#include "constexp.h" +#include + +constexpr unsigned int fibonacci(const unsigned int n) { + if (n == 1 || n == 2) { + return 1; + } + + return fibonacci(n - 2) + fibonacci(n - 1); +} + +void constexp::test() { + std::cout << "Fibonacci(10): "; + for (const unsigned int n : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}) { + std::cout << fibonacci(n) << " "; + } + std::cout << std::endl; + + int arr_1[fibonacci(10)]; + std::cout << "Array is " << sizeof(arr_1) / sizeof(int) << " items long" + << std::endl; + + constexpr unsigned int arr_2_len = 10; + int arr_2[arr_2_len]; + std::cout << "Array is " << sizeof(arr_2) / sizeof(int) << " items long" + << std::endl; +} diff --git a/src/constexp.h b/src/constexp.h new file mode 100644 index 0000000..362b4ff --- /dev/null +++ b/src/constexp.h @@ -0,0 +1,5 @@ +#pragma once + +namespace constexp { +void test(); +}; diff --git a/src/main.cpp b/src/main.cpp index fbea74c..e7a4ebb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -3,6 +3,7 @@ #include "version.h" +#include "constexp.h" #include "null.h" int main(int argc, char **argv) { @@ -10,8 +11,13 @@ int main(int argc, char **argv) { std::cout << "Running " << PROJECT_NAME << ", version " << VERSION << "\n" << std::endl; + std::cout << "Null test:" << std::endl; null::test(); + std::cout << "\n" + << "Constexpr test:" << std::endl; + constexp::test(); + std::cout << "\nExiting" << std::endl; return EXIT_SUCCESS;