revision #1: 更新第二章中已维护的代码

This commit is contained in:
Changkun Ou
2018-04-02 00:28:05 +02:00
parent 11efa38dba
commit 838d30ef5a
28 changed files with 460 additions and 111 deletions

50
code/2/2.2.constexpr.cpp Normal file
View File

@@ -0,0 +1,50 @@
//
// 2.2.constexpr.cpp
// chapter 2 language usability
// modern cpp tutorial
//
// created by changkun at changkun.de
//
#include <iostream>
#define LEN 10
int len_foo() {
int i = 2;
return i;
}
constexpr int len_foo_constexpr() {
return 5;
}
// error in c++11
// constexpr int fibonacci(const int n) {
// if(n == 1) return 1;
// if(n == 2) return 1;
// return fibonacci(n-1) + fibonacci(n-2);
// }
// ok
constexpr int fibonacci(const int n) {
return n == 1 || n == 2 ? 1 : fibonacci(n-1) + fibonacci(n-2);
}
int main() {
char arr_1[10]; // legal
char arr_2[LEN]; // legal
int len = 10;
// char arr_3[len]; // illegal
const int len_2 = len + 1;
char arr_4[len_2]; // legal
// char arr_5[len_foo()+5]; // illegal
char arr_6[len_foo_constexpr() + 1]; // legal
// 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
std::cout << fibonacci(10) << std::endl;
return 0;
}