nullptr
C++11 引入了 nullptr 关键字,专门用来区分空指针、0。
#include <iostream>
#include <type_traits>
void foo(char *);
void foo(int);
int main() {
if (std::is_same<decltype(NULL), decltype(0)>::value)
std::cout << "NULL == 0" << std::endl;
if (std::is_same<decltype(NULL), decltype((void*)0)>::value)
std::cout << "NULL == (void *)0" << std::endl;
if (std::is_same<decltype(NULL), std::nullptr_t>::value)
std::cout << "NULL == nullptr" << std::endl;
foo(0); // will call foo(int)
// foo(NULL); // doesn't compile
foo(nullptr); // will call foo(char*)
return 0;
}
void foo(char *) {
std::cout << "foo(char*) is called" << std::endl;
}
void foo(int i) {
std::cout << "foo(int) is called" << std::endl;
}
g++ -std=c++17 2.01.nullptr.cpp -o nullptr.out
constexpr
#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;
constexpr int len_2_constexpr = 1 + 2 + 3;
// char arr_4[len_2]; // illegal, but ok for most of the compilers
char arr_4[len_2_constexpr]; // 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;
}
g++ -std=c++17 2.02.constexpr.cpp -o constexpr.out
如果需要都输出加个循环即可;
for(int i=1;i<11;i++)
{
std::cout << fibonacci(i) << std::endl;
}