gpt4 book ai didi

c++ - 什么是编译时已知的值?

转载 作者:可可西里 更新时间:2023-11-01 18:20:02 26 4
gpt4 key购买 nike

我正在学习 C++ 编程语言,我的书中有一章向我介绍了常量的概念:

A constexpr symbolic constant must be given a value that is known at compile time

什么是编译时已知的值?为什么我们需要它们?

最佳答案

A constant expression表示可以由编译器在编译时(即程序运行之前,编译期间)评估的表达式。

常量表达式可用于初始化标有constexpr (referring to the C++11 concept) 的变量。这样的变量给编译器提示它可以在编译时求值(并且可能节省宝贵的运行时周期),例如

#include <iostream>

constexpr int factorial(int n) // Everything here is known at compile time
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}

int main(void)
{
constexpr int f = factorial(4); // 4 is also known at compile time
std::cout << f << std::endl;
return 0;
}

Example

如果您不提供常量表达式,编译器实际上无法在编译时完成所有这些工作:

#include <iostream>

constexpr int factorial(int n) // Everything here is known at compile time
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}

int main(void)
{
int i;
std::cin >> i;
const int f = factorial(i); // I really can't guess this at compile time..
// thus it can't be marked with constexpr
std::cout << f << std::endl;
return 0;
}

Example

执行编译时额外工作而不是运行时工作的好处是性能提升,因为您的编译程序可能能够使用预先计算的值,而不必每次都从头开始计算它们.常量表达式越昂贵,您的程序获得的 yield 就越大。

关于c++ - 什么是编译时已知的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26721030/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com