C++ 的 constexpr函数

等级 5283 次按键

constexpr 阶乘函数在用于初始化 constexpr 变量时于编译期求值,也可以像普通函数一样调用。输出 120、5040 和 720。

C++ 代码

// constexpr:参数为常量时可以在编译期求值
1constexpr int factorial(int n) {
// 递归:n! = n × (n - 1)!,n <= 1 时为 1
2 return (n <= 1) ? 1 : n * factorial(n - 1);
3}
4
// constexpr 变量强制在编译期求值:120
5constexpr int compiletime = factorial(5);
// 普通变量:同一个函数也可以像普通函数一样使用(5040)
6int runtime = factorial(7);
7
// 输出“Compile-time: 120”
8cout << "Compile-time: " << compiletime << endl;
// 输出“Runtime: 5040”
9cout << "Runtime: " << runtime << endl;
// 在表达式中直接调用:6! = 720
10cout << "Direct: " << factorial(6) << endl;

运行结果

Compile-time: 120
Runtime: 5040
Direct: 720
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 C++ 代码中需要输入的符号及其出现次数。

  • <× 19
  • ;× 6
  • "× 6
  • (× 6
  • )× 6
  • :× 4
  • =× 3
  • -× 2
  • ?× 1
  • {× 1

C++ 等级 5 的更多代码示例

← 返回 C++ 打字练习