constexpr/constexpr-1-statass.cpp - The same program - with results statically asserted. | Lecture 6 - slide 33 : 40 Program 2 |
// The same examples again, with static_assert's of results (instead of output at run time). // Compiles without errors, with g++ constexpr-1-statass.cpp -std=c++11 -c // This means that all asserted results are correctly computed at compile time. #include <iostream> constexpr int I1 = 5, I2 = 7, I3 = 9; constexpr int I4 = (I1 % 2 == 0) ? I2 : I3; constexpr bool even(int n){ return n % 2 == 0; } constexpr int I5 = even(I1) ? I2 : I3; // Eqvivalent to I4 static_assert(I5==I3, "Expected: I5=I3"); constexpr long int fac(int n){ return (n == 0) ? 1 : n * fac(n - 1); } constexpr long int FAC5 = fac(5); static_assert(FAC5==120, "Expected: FAC5 is 120"); constexpr long int FAC10 = fac(10); static_assert(FAC10==3628800, "Expected: FAC10 is 362800"); constexpr long int fib(int n){ return (n == 0) ? 0 : (n == 1) ? 1 : fib(n - 1) + fib(n - 2); } constexpr long int FIB20 = fib(20); static_assert(FIB20==6765, "Expected: FIB20 is 6765");